Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove unwanted space in between a string [duplicate]

Tags:

python

I wanna know how to remove unwanted space in between a string. For example:

>>> a = "Hello    world" 

and i want to print it removing the extra middle spaces.

Hello world

like image 508
speed Avatar asked May 26 '11 17:05

speed


2 Answers

This will work:

" ".join(a.split())

Without any arguments, a.split() will automatically split on whitespace and discard duplicates, the " ".join() joins the resulting list into one string.

like image 184
Ed L Avatar answered Nov 18 '22 23:11

Ed L


Regular expressions also work

>>> import re
>>> re.sub(r'\s+', ' ', 'Hello     World')
'Hello World'
like image 22
Matty K Avatar answered Nov 19 '22 00:11

Matty K