I l@ve RuBoard Previous Section Next Section

3.5 Trimming Space from the Ends of a String

Credit: Luther Blissett

3.5.1 Problem

You need to work on a string without regard for any extra leading or trailing spaces a user may have typed.

3.5.2 Solution

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 |

3.5.3 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, 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.

3.5.4 See Also

The Library Reference section on string methods; Java Cookbook Recipe 3.12.

    I l@ve RuBoard Previous Section Next Section