如何在Python中用正则表达式替换一个空格?

2024-03-13

例如:

T h e   t e x t   i s   w h a t   I   w a n t   t o   r e p l a c e

我想要这样的结果:

The text is what I want to replace

我用 shell、sed 尝试过,

 echo 'T h e   t e x t   i s   W h a t   I  w a n t   r e p l a c e'|sed -r "s/(([a-zA-Z])\s){1}/\2/g"|sed 's/\  / /g'

成功了。 但我不知道如何替换它python。有人可以帮助我吗?


如果您只想转换每个字符之间有空格的字符串:

>>> import re
>>> re.sub(r'(.) ', r'\1', 'T h e   t e x t   i s   w h a t   I   w a n t   t o  r e p l a c e')
'The text is what I want to replace'

或者,如果您想删除所有单个空格并将空格替换为一个:

>>> re.sub(r'( ?) +', r'\1', 'A B  C   D')
'AB C D'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中用正则表达式替换一个空格? 的相关文章

随机推荐