pythonstringtrim

How to remove leading and trailing spaces from a string?


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])

Solution

  • 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.