Computer >> Computer tutorials >  >> Programming >> Python

How to remove all trailing and leading whitespace in a string in Python?


To remove all trailing and leading whitespace in a string, we can use the method strip() in String class that gets rid of both these whitespaces. You can use it as follows:

>>> '   Hello People   '.strip()
'Hello People'

If you only want to remove leading or trailing whitespace use lstrip() or rstrip() respectively.

>>> '   Hello People'.lstrip()
'Hello People'
>>> 'Hello People   '.rstrip()
'Hello People'