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

3
例如:
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中进行替换。有人能帮我吗?

3个回答

5
如果您只想将带有字符间空格的字符串转换为无空格字符串:
>>> 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'

@kEvin不会替换字符串开头的空格。 - agf
@agf 是的,我提供了一种替代方法。 - eph

3

仅供娱乐,这里提供一个使用字符串操作的非正则表达式解决方案:

>>> 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'
< p >(根据评论,我将< code >_更改为< code >\ 0 (空字符)。)

你可能想使用'\0'而不是'_' - mu is too short
在我看来,比起正则表达式,这个要容易理解多了。 - Paul Hildebrandt

1

只是为了好玩,还有两种方法可以做到这一点。这两种方法都假定你想要的每个字符后面严格地有一个空格。

>>> 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'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接