开发者

Anyone know a good regex to remove extra whitespace? [duplicate]

This question already has answers here: 开发者_如何学编程 Closed 12 years ago.

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


import re    
re.sub("\s+"," ",string)


Does it need to be a regex?

I'd just use

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


sed

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜