FAQ
overflow

Great Answers to
Questions About Everything

QUESTION

I've come to the conclusion that python has a function for just about everything I could ask for. It's just a matter of actually finding these functions. Is there a function that will trim not only spaces for whitespace, but also tabs?

Thanks :)

{ asked by Chris }

ANSWER

Whitespace on the both sides:

s = "  \t a string example\t  "
s = s.strip()

Whitespace on the right side:

s = s.rstrip()

Whitespace on the left side:

s = s.lstrip()

As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:

s = s.strip(' \t\n\r')

This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string.

{ answered by James Thompson }
Tweet