Recipe 1.5. Trimming Space from the Ends of a String
Credit: Luther Blissett
Problem
You need to work on a string
without regard for any extra leading or trailing spaces a user may
have typed.
Solution
That's what the
lstrip, rstrip, and
strip methods of string objects are for. Each
takes no argument and returns a copy of the starting string, shorn of
whitespace on either or both sides:
>>> x = ' hej '
>>> print '|', x.lstrip( ), '|', x.rstrip( ), '|', x.strip( ), '|'
| hej | hej | hej |
Discussion
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 (as covered previously in Recipe 1.4), so may you need to remove
all whitespace (blanks, tabs, newlines, etc.) from either or both
ends. Because this need is frequent, Python string objects supply
this functionality through three of their many methods. Optionally,
you may call each of these methods with an argument, a string
composed of all the characters you want to trim from either or both
ends instead of trimming whitespace characters:
>>> x = 'xyxxyy hejyx yyx'Note that in these cases the leading and trailing spaces have been
>>> print '|'+x.strip('xy')+'|'
| hejyx |
left in the resulting string, as have the 'yx'
that are followed by spaces: only all the occurrences of
'x' and 'y' at
either end of the string have been removed from the resulting string.
See Also
The Library Reference section on string
methods; Recipe 1.4;
Java Cookbook recipe 3.12.