Python Remove Leading and Trailing Spaces from String

Python3 Examples

To remove leading and trailing spaces from a string, Python can use thestrip()method.

Here is an example of how to use it:

Example

original_string = " This is a string with spaces "
stripped_string = original_string.strip()
print(stripped_string)

Executing the above code will remove the leading and trailing spaces from the string. The output result is as follows:

This is a string with spaces

However, if the string contains\nand other characters, and you only want to remove spaces, you need to explicitly specify it on the strip() method, as shown in the following code:

Example

my_string = " \nPython "

print(my_string.strip(" "))
The output result is:

Python
We can also use regular expressions to remove leading and trailing spaces from a string:

Example

import re

my_string  = " Hello Python "
output = re.sub(r'^\s+|\s+$', '', my_string)

print(output)

Executing the above code will output the following result:

Hello python

The strip() method will remove all whitespace at the beginning and end of the string (including spaces, tabs, and newlines).

In addition, Python provides two methods for removing leading and trailing spaces from a string:

  • lstrip()-- Remove spaces at the beginning of the string.
  • rstrip()-- Remove spaces at the end of the string.

Example

original_string = " This is a string with spaces "
left_stripped_string = original_string.lstrip()  # Remove leading spaces
right_stripped_string = original_string.rstrip()  # Remove trailing spaces

print(left_stripped_string)
print(right_stripped_string)

Executing the above code will output the following result:

This is a string with spaces   
    This is a string with spaces

Python3 Examples

Other Extensions