【问题标题】:How to replace just one whitespace with regex in python?如何在python中用正则表达式替换一个空格?
【发布时间】:2011-11-18 09:41:40
【问题描述】:
例如:
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 中替换它。有人可以帮帮我吗?
【问题讨论】:
标签:
python
regex
replace
removing-whitespace
【解决方案1】:
如果您只想转换每个字符之间有空格的字符串:
>>> 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'
【解决方案2】:
只是为了好玩,这里是一个使用字符串操作的非正则表达式解决方案:
>>> text = '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'
>>> text.replace(' ' * 3, '\0').replace(' ', '').replace('\0', ' ')
'The text is what I want to replace'
(根据评论,我将_ 更改为\0(空字符)。)
【解决方案3】:
只是为了好玩,还有两种方法可以做到这一点。这些都假设在您想要的每个字符之后都有一个严格的空格。
>>> s = "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 "
>>> import re
>>> pat = re.compile(r'(.) ')
>>> ''.join(re.findall(pat, s))
'The text is what I want to replace'
使用字符串切片更简单:
>>> s[::2]
'The text is what I want to replace'