Skip to content Skip to sidebar Skip to footer

How To Replace Just One Whitespace With Regex In 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,

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

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

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

Post a Comment for "How To Replace Just One Whitespace With Regex In Python?"