How to trim white spaces from the user input in Python

Let’s say you need to accept user input but without the white spaces. The strip() method of the string object can be used to delete any white space characters from a string.

>>> s1 = ' Whitespace '
>>> s1
' Whitespace '
>>> s2 = s1.strip()
>>> s2
'Whitespace'

The strip() method gets rid of any white space at the beginning and the end of a string.
You can strip unwanted white space only at the beginning or only at the end of a string.

>>> s1 = ' Whitespace '
>>> s2 = s1.lstrip()
>>> s2
'Whitespace '
>>> s3 = s1.rstrip()
>>> s3
' Whitespace'

Leave a Reply