14

In python I have, for example, the following string:

a = "Sentence  with     weird    whitespaces"

I want the same string with extended whitespaces replaced by just one, so the final string would read

 'Sentence with weird whitespaces'

I found a solution myself, but is there a better/shorter one?

' '.join([x for x in a.split(' ') if len(x)>0])
Alex
  • 41,580
  • 88
  • 260
  • 469
  • have you tried using [`re.sub`](https://docs.python.org/2/library/re.html#re.sub)? – R Nar May 25 '16 at 18:48
  • see this link: http://stackoverflow.com/questions/2077897/substitute-multiple-whitespace-with-single-whitespace-in-python – SD433 May 25 '16 at 18:48
  • If you're looking to make it shorter, you could replace `if len(x).0` with `if x`. Note that this doesn't make it *better*, just shorter. (Code-golf disclaimer) – DJMcMayhem May 25 '16 at 18:52
  • Yes sure, I just saw that myself. Adding an empty string is just 'fine' (maybe not from a performance point-of-view, but still) – Alex May 25 '16 at 18:53

3 Answers3

34

You can use:

import re
a = re.sub(' +',' ',a)
Keiwan
  • 8,031
  • 5
  • 36
  • 49
11
" ".join(a.split())

pulled this from one of the duplicates for your question

WildCard
  • 527
  • 3
  • 8
  • Right, I can omit my length check. Adding an empty string to a string does not change string. I really should call it a day... – Alex May 25 '16 at 18:52
1

Your solution is already very pythonic, I often use a more readable version:

sentence = "Sentence  with     weird    whitespaces"

while "  " in sentence:
    sentence = sentence.replace("  ", " ")

(Replace double spaces by one while double spaces are in string).

Hope this helps!

linusg
  • 6,289
  • 4
  • 28
  • 78