Credit: Luther Blissett
You need to work on a string without regard for any extra leading or trailing spaces a user may have typed.
That’s what the
lstrip
,
rstrip
, and
strip
methods of string objects are for. Each
takes no argument and returns the starting string, shorn of
whitespace on either or both sides:
>>> x = ' hej '
>>> print '|', x.lstrip(), '|', x.rstrip(), '|', x.strip( ), '|'
| hej | hej | hej |
Just as you may need to add space to either end of a string to align that string left, right, or center in a field of fixed width, so may you need to remove all whitespace (blanks, tabs, newlines, etc.) from either or both ends. Because this is a frequent need, Python string objects supply this functionality through their methods.
Get Python Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.