Stripping and Parsing: lstrip(), rstrip(), strip()

When you parse strings, you often need to get rid of whitespace. This is what the stripping functions do. They're handy and convenient; I think you'll use them quite a bit.

Whitespace Variables

Whitespace is defined by the public variable whitespace in the string module. This code contains a tab and spaces:

>>> whitespace
'\ 11 '

The lstrip(s) (left strip) function removes leading whitespace (on the left) in the string. The rstrip(s) (right strip) function removes the trailing whitespace (on the right). The strip(s) function removes both leading and trailing whitespace. Here's an example of all three:

 >>> str = " String String " >>> lstrip(str) 'String String ' >>> rstrip(str) ' String String' ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython 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.