Remove unwanted space between the line

I want to know how to remove unwanted space between a string. For instance:

>>> a = "Hello    world" 

and I want to print it, removing the extra gaps.

Hello World

+5
source share
2 answers

This will work:

" ".join(a.split())

Without any arguments, it a.split()will automatically be divided into spaces and discard duplicates; it " ".join()combines the resulting list into one line.

+20
source

Regular expressions also work

>>> import re
>>> re.sub(r'\s+', ' ', 'Hello     World')
'Hello World'
+11
source

All Articles