+3 votes
3 views
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"

2 Answers

+2 votes
by (26.5k points)
edited by

You can use mystring , 

myString.strip()

Or 

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.

Ex-

‘Hey ‘ .strip()

>>>’Hey’

‘ Hey ‘.strip()

>>>’Hey’

‘ Hey’.strip()

>>>’Hey’

‘harsh has a dog ’.strip()

>>>’harsh has a dog’

‘    Hey \n’.strip(“ “)

>>>’Hey\n’

 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

...