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中替换它。有人可以帮助我吗?

4

3 回答 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'
于 2011-09-16T04:33:32.097 回答
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(空字符)。)

于 2011-09-16T04:40:12.797 回答
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'
于 2011-09-18T02:21:28.177 回答