19

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

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
speed
  • 205
  • 1
  • 3
  • 5
  • (If you use
     tags you can force SO to show the spaces :) )
    – marnir May 26 '11 at 17:53
  • @Tim: And if you indent your code by 4 spaces, you save us the work of removing all the `
    `-tags used by people who don't bother to look up the SO formatting options.
    – Björn Pollex May 26 '11 at 17:56
  • Ah, of course, I forgot. (I'm very much a SO newbie, in terms of actually posting!) – marnir May 27 '11 at 14:26

2 Answers2

47

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.

Ed L
  • 1,947
  • 2
  • 17
  • 30
22

Regular expressions also work

>>> import re
>>> re.sub(r'\s+', ' ', 'Hello     World')
'Hello World'
Matty K
  • 3,781
  • 2
  • 22
  • 19
  • This worked best for me to remove trailing, leading and middle white space, and remove \n newline characters. – Ryan B Apr 03 '20 at 05:22
  • 1
    This is a good way to go if you are using Pandas, specifically `df['full_name'] = df['full_name'].replace('\s+', ' ', regex=True)` – ProfessorPorcupine Jun 28 '22 at 19:35