How to remove extra spaces from string in python?

How to remove extra spaces from string in python?

strip() method in python removes both leading and trailing whitespaces from a string. If you only want to remove either leading or trailing whitespaces you can use lstrip() or rstrip() methods.

General solution in 2 lines of code for removing extra spaces from string

strip() example:

 myString = "   Halo, This   is some text   "

myString = myString.strip()

print(myString)

Output:

Halo, This   is some text

lstrip() example:

 myString = "'   Halo, This   is some text   '"

myString = myString.strip()

print(myString)

Output:

'Halo, This   is some text   '

rstrip() example:

 myString = "'   Halo, This   is some text   '"

myString = myString.strip()

print(myString)

Output:

'   Halo, This   is some text'
Now what about the extra spaces in between, we can implement the a more general solution in just two lines of code by using regular expression. If two or more spaces occur adjacent to each other we replace them with a single space. i.e. " +" will be replaces by " ".
import re

myString = "'  Halo, This   is some text   '"

myString = re.sub(' +', ' ', myString)

print(myString)

Output:

'Halo, This is some text'

Comments