如何用Python中的正则替换一个空格?

发布于 2024-12-05 06:45:31 字数 417 浏览 1 评论 0原文

例如:

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

for example:

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

I want the result like this:

The text is what I want to replace

I tried that with 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'

it's successfully.
but I don't know how to replace this in python. could anybody help me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

诗化ㄋ丶相逢 2024-12-12 06:45:31

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

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

或者,如果要删除所有单个空格,然后将Whitespaces替换为一个:

>>> re.sub(r'( ?) +', r'\1', 'A B  C   D')
'AB C D'

If you just want to convert a string that has whitespace between each chars:

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

Or, if you want to remove all single whitespace and replace whitespaces to just one:

>>> re.sub(r'( ?) +', r'\1', 'A B  C   D')
'AB C D'
可是我不能没有你 2024-12-12 06:45:31

只是为了好玩,这里是一个使用字符串操作的非正则表达式解决方案:(

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

Just for kicks, here is a non-regex solution using string operations:

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

(Per the comment, I changed the _ to \0 (null character).)

烟沫凡尘 2024-12-12 06:45:31

只是为了娱乐,还有另外两种方法。这些都认为,每个角色都严格存在一个空间。

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

Just for fun, two more ways to do it. These both assume there is strictly a space after every character that you want.

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

Even easier, using string slicing:

>>> s[::2]
'The text is what I want to replace'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文