Does anyone know a good regex to remove extra spaces?

Possible duplicate:
Replace multiple spaces with a single space in Python

trying to figure out how to write a regular expression that is given for a string:

"hi     this       is a  test"

I can turn it into

"hi this is a test"

where spaces are normalized to only one space

any ideas? Many thanks

+3
source share
3 answers
import re    
re.sub("\s+"," ",string)
+7
source

Do I need to be a regular expression?

I would just use

new_string = " ".join(re.split(s'\s+', old_string.strip()))
0
source

Sed

 sed 's/[  ]\{2,\}/ /g'
0
source

Source: https://habr.com/ru/post/1748600/


All Articles