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

3 投票
3 回答
2330 浏览
提问于 2025-04-17 02:25

比如说:

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 个回答

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'
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(空字符)。)

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'

撰写回答