Search code snippets, questions, articles...

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()
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

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'

Search Index Data (The code snippet can also be found with below search text)

trim python string
Was this helpful?