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

我是研究僧i 提交于 2021-02-19 03:47:07

问题


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


回答1:


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



回答2:


Does it need to be a regex?

I'd just use

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



回答3:


sed

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


来源:https://stackoverflow.com/questions/2977905/anyone-know-a-good-regex-to-remove-extra-whitespace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!