Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best replace multiple whitespaces by one (in python)? [duplicate]

Tags:

python

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])
like image 316
Alex Avatar asked May 25 '16 18:05

Alex


2 Answers

You can use:

import re
a = re.sub(' +',' ',a)
like image 89
Keiwan Avatar answered Sep 28 '22 01:09

Keiwan


" ".join(a.split())

pulled this from one of the duplicates for your question

like image 45
WildCard Avatar answered Sep 28 '22 01:09

WildCard