views:

1214

answers:

2

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 :)

+1  A: 

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)
ars
You didn't compile your regex. You need to make it be `pat = re.compile(r'\s+')`
Evan Fosmark
fixed; thanks evan.
ars
+10  A: 

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.

James Thompson
this function does not seem to strip preceding tabs..
Chris
strip() takes in an arguemnt to tell it what to trip. Try: strip(' \t\n\r')
thedz
`str` is a type, so you should avoid using it as a variable name..
John Fouhy