Last modified: Apr 08, 2023 By Alexander Williams

5 Ways to Remove Whitespace From End of String in Python

Using rstrip

# Define a string with whitespace at the end
my_string = "Hello World      "

# Use the rstrip() method to remove whitespace from the end of the string
my_string = my_string.rstrip()

# Print the updated string without whitespace at the end
print(my_string)

Output:

Hello World

Using slicing

# Define a string with whitespace at the end
my_string = "Hello World      "

# Use slicing to remove whitespace from the end of the string
my_string = my_string[:-len(my_string.rstrip())]

# Print the updated string without whitespace at the end
print(my_string)

Output:

Hello World

Using regular expressions

import re

# Define a string with whitespace at the end
my_string = "Hello World      "

# Use a regular expression to remove whitespace from the end of the string
my_string = re.sub(r'\s+$', '', my_string) # \s+$ match one or more whitespace characters at the end of the string

# Print the updated string without whitespace at the end
print(my_string)

Output:

Hello World

Using a loop

# Define a string with whitespace at the end
my_string = "Hello World      "

# Loop through the string from right to left, removing whitespace
i = len(my_string) - 1
while i >= 0 and my_string[i].isspace():
    i -= 1
my_string = my_string[:i+1]

# Print the updated string without whitespace at the end
print(my_string)

 Output:

Hello World

Using a list comprehension

# Define a string with whitespace at the end
my_string = "Hello World      "

# Use a list comprehension to remove whitespace from the end of the string
my_string = ''.join([char for char in my_string if not char.isspace() or char == my_string.strip()[-1]])

# Print the updated string without whitespace at the end
print(my_string)

  Output:

Hello World