如何用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
我希望这样的结果:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只想转换每个字符之间具有空格的字符串:
或者,如果要删除所有单个空格,然后将Whitespaces替换为一个:
If you just want to convert a string that has whitespace between each chars:
Or, if you want to remove all single whitespace and replace whitespaces to just one:
只是为了好玩,这里是一个使用字符串操作的非正则表达式解决方案:(
根据评论,我将
_
更改为\0
(空字符)。)Just for kicks, here is a non-regex solution using string operations:
(Per the comment, I changed the
_
to\0
(null character).)只是为了娱乐,还有另外两种方法。这些都认为,每个角色都严格存在一个空间。
使用字符串切片更容易:
Just for fun, two more ways to do it. These both assume there is strictly a space after every character that you want.
Even easier, using string slicing: