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

In Python, How to remove trailing and leading whitespace from str  ?

For instance check this:

" Hey" --> "Hey"
" Hey"  --> "Hey"
"Hey"  --> "Hey"
"Harsh has a dog" --> "Harsh has a dog"

3 Answers

+2 votes
by (46.1k points)
edited by

You can use mystring , 



use strip:

myfile= [ " Hey", " Hey", "Hey", "Harsh has a dog" ]

for phrase in myfile:
    print phrase.strip()

+1 vote
by (10.9k points)
edited by

@Suresh , You can use the .strip() method to remove whitespaces but it has a disadvantage which is it removes other whitespace characters like \t , \n etc , so you need to specify the whitespaces as an argument.


‘Hey ‘ .strip()


‘ Hey ‘.strip()


‘ Hey’.strip()


‘harsh has a dog ’.strip()

>>>’harsh has a dog’

‘    Hey \n’.strip(“ “)


 If you want to remove only one white space from the string use:

def striponeSpace(a):

   if a.endswith(" "): a = a[:-1]

  if a.startswith(" "):a = a[1:]

    return a

 >>> striponeSpace("   Hey ")

'  Hey'

You can also use myString.rstrip() to remove all the trailing whitespaces from the string and myString.lstrip() to remove all the leading whitespaces from the string

0 votes
by (107k points)

Python trim method is called strip:




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

Related questions

+3 votes
3 answers
asked May 28, 2019 in Python by Anvi (10.2k points)
0 votes
1 answer
+1 vote
2 answers
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !