3

Possible Duplicate:
Substitute multiple whitespace with single whitespace in Python

trying to figure out how to write a regex that given the string:

"hi     this       is a  test"

I can turn it into

"hi this is a test"

where the whitespace is normalized to just one space

any ideas? thanks so much

Community
  • 1
  • 1
James
  • 15,085
  • 25
  • 83
  • 120

3 Answers3

11
import re    
re.sub("\s+"," ",string)
Stedy
  • 7,359
  • 14
  • 57
  • 77
0

Does it need to be a regex?

I'd just use

new_string = " ".join(re.split(s'\s+', old_string.strip()))
Ian Clelland
  • 43,011
  • 8
  • 86
  • 87
0

sed

 sed 's/[  ]\{2,\}/ /g'
jim mcnamara
  • 16,005
  • 2
  • 34
  • 51