Trim or remove begin and end spaces from a python string

To remove the leading and trailing space from a string - the python strip() method can be used.

my_str = "  This string contains spaces.  "

#trim python string using strip() method
trimmmed_str = my_str.strip()

#remove leading(beginning) whitespace
lstr = my_str.lstrip()

#remove trailing(end) whitespace
rstr = my_str.rstrip()

In the code snippet, we have a string variable my_str that contains a sentence. It has some space at its beginning and end. We are removing this space using the .strip() method of python string that will remove the space.

We can use the below python methods to remove trailing and leading whitespaces from a python string.

str.strip() - remove space from both sides

If you want to remove space or whitespace from both sides of the string, you can use the strip() method, Below is the example for that.

str = '  Hello World '
new_str = str.strip()
# -> 'Hello World'

str.lstrip() - remove whitespace from begin

The Python string method lstrip() can be used to remove whitespace from the beginning of the string. Below is the code example

str = '  Hello World  '
new_str = str.lstrip()
# -> 'Hello World  '

str.rstrip() - remove whitespace from end

To remove trailing whitespace from a string, the python rstrip() method is used. It will remove all the spaces from the end of the string.\

Code Example:

str = '  Hello World  '
new_str = str.lstrip()
# -> '  Hello World'
Was this helpful?