+3 votes
3 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 (107k 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 (22.4k 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
0 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...