Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

 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?

like image 752
kEvin Avatar asked Feb 18 '26 02:02

kEvin


1 Answers

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'
like image 51
eph Avatar answered Feb 19 '26 18:02

eph