Trim a string means removing blank spaces or white spaces from left and right of the string where left means from the beginning and right means from the end.

There is no straight forward trim function in python but it provides strip(), lstrip() and rstrip() functions to remove empty spaces from a string.

This article will explain how to trim spaces around a string in python.
strip() function
strip() function removes all leading and trailing spaces from a string. That is, spaces before and after a string. This function takes no arguments. Example,

str = '    codippa.com   '
# print the string
print('Raw string:', str, 'with spaces')
# remove spaces
nospace_str = str.strip()
# print trimmed string
print('Trimmed string:', nospace_str, 'without spaces')

Above example will output

Raw string:     codippa.com     with spaces
Trimmed string: codippa.com without spaces

Note that strip() function will return a new string with spaces removed and it will not modify the original string.

lstrip() function
lstrip() stands for left strip and removes all spaces to the left of the string. Spaces to the right of the string are not removed. Example,

str = '    codippa.com   '
# print the string
print('Raw string:', str)
# remove spaces
nospace_str = str.lstrip()
# print trimmed string
print('Trimmed string:', nospace_str, 'without left spaces')

Output of above code will be

Raw string:     codippa.com     with spaces
Trimmed string: codippa.com     without left spaces

Above output shows that all the spaces from left end of the string are removed but the spaces from the right end are not removed.
Note that lstrip() will return a new string and will not modify the original string. It will still have spaces around.

rstrip() function
As its name suggests, this method removes all spaces from the right end of the string while spaces at the left of the string are not removed. Example,

str = '    codippa.com   '
# print the string
print('Raw string:', str)
# remove right spaces
nospace_str = str.rstrip()
# print trimmed string
print('Trimmed string:', nospace_str, 'without right spaces')

Output of above code will be

Raw string:     codippa.com     with spaces
Trimmed string:     codippa.com without right spaces

rstrip() will not modify the original string but return a new string after removing right white spaces.

If you are sure about the direction of spaces, then use appropriate method, that is, lstrip() for removing left white spaces and rstrip() for right spaces. But in case, you don’t know where the spaces will be present, then use strip().
Also, remember that these methods will remove spaces from the beginning and end of the string but not from its middle.
Hit the clap below if the article was useful for you.

Leave a Reply