Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+3 votes
10 views
in Python by (10.2k 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

3 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
by (106k 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:-

0 votes
by (20.3k points)

For leading and trailing whitespace, you can do like this:

s = '   foo    \t   '

print s.strip() # prints "foo"

Otherwise, you can just use the regular expression this way:

import re

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

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

print pat.sub('', s) # prints "foobar"

Related questions

+3 votes
3 answers
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...