Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+3 votes
11 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"

3 Answers

+2 votes
by (46k 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()

If you are looking for upskilling yourself in python you can join our Python Certification and learn from an industry expert. 

+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

0 votes
by (106k points)

Python trim method is called strip:

str.strip()

str.lstrip()

str.rstrip()

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
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...