Fix Python – How to remove leading and trailing spaces from a string?

Question

Asked By – fpena06

I’m having a hard time trying to use .strip with the following line of code:

f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])

Now we will see solution for issue: How to remove leading and trailing spaces from a string?


Answer

You can use the strip() method to remove trailing and leading spaces:

>>> s = '   abd cde   '
>>> s.strip()
'abd cde'

Note: the internal spaces are preserved.

This question is answered By – Anshuma

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0