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 :)
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 :)
For leading and trailing whitespace:
s = ' foo \t '
print s.strip()
Otherwise, a regular expression works:
import re
pat = re.compile(r'\s+')
s = ' \t foo \t bar \t '
print pat.sub('', s)
Whitespace on the both sides:
str = " \t a string example\t "
str = str.strip()
Whitespace on the right side:
str = str.rstrip()
Whitespace on the left side:
str = str.lstrip()
As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:
str = str.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.