How to replace just one whitespace with regex in python?

丶灬走出姿态 提交于 2019-12-23 16:58:30

问题


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?


回答1:


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'



回答2:


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).)




回答3:


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'


来源:https://stackoverflow.com/questions/7440175/how-to-replace-just-one-whitespace-with-regex-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!