+3 votes
in Python by (3.4k points)
edited by

How can I trim whitespace using python, I want to delete all spaces and tabs?  For E.x.

\t AT\t → At

2 Answers

0 votes
by (2k points)
edited by

To trim the whitespace in python use strip:

str.strip() #trim
str.lstrip() #lefttrim
str.rstrip() #righttrim

For your case:

s = "  \t AT\t  "
s = s.strip()

0 votes
ago by (50.5k points)

For leading and trailing whitespace:

s = '   foo    \t   '

print s.strip()

In other cases use a regular expression:

import re

pat = re.compile(r'\s+')

s = '  \t  foo   \t   bar \t  '

print pat.sub('', s) 

You can use the following video tutorials to clear all your doubts:-