在python中如何用regex替换一个空格?

2024-04-25 04:35:04 发布

您现在位置:Python中文网/ 问答频道 /正文

例如:

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

我想要这样的结果:

^{pr2}$

我用贝壳试过了,赛德

 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中替换它。有人能帮我吗?在


Tags: echosedzapr2
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'

(根据注释,我将_改为\0(空字符)

只是为了好玩,还有两种方法。它们都假设在你想要的每个字符后面都有一个空格。在

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

更简单的是,使用字符串切片:

^{pr2}$

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

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

或者,如果要删除所有单个空白并将空白替换为一个:

^{pr2}$

相关问题 更多 >