Re.sub replace spaces with comma

I have a list of items that looks like this:

 2.4       -2.0           4.3
-6.0       12.5           1.0

      

I would like to remove all those spaces and replace them with "," (comma), except for the spaces before the first numbers (they should just be removed (spaces) and not replaced with anything). Therefore, the top inline elements should look like this after replacement:

2.4,-2.0,4.3
-6.0,12.5,1.0

      

Not this way:

,2.4,-2.0,4.3
,-6.0,12.5,1.0

      

This is what the following code does:

newStrings = []
for s in strings:
    newStrings.append(re.sub('\s+', ',', s))

      

What regex for re.sub should be used to achieve this? Thank.

+3


source to share


2 answers


To remove leading and trailing spaces, you can use .strip()

and then replace consecutive whitespace characters with a regular expression \s+

:



>>> import re
>>> s = " 2.4       -2.0           4.3"
>>> re.sub("\s+", ",", s.strip())
'2.4,-2.0,4.3'

      

+5


source


There are many solutions ... This doesn't even cover the whole topic briefly, but it works:

Quick solution :



In [1]: import re
   ...: d_in = "strip \t\r\n\x00er \ter\rMY\   nr\x00 \t\r\nSPAC       ES\x00  ! "
   ...: d_out = re.sub("\s+", r",", d_in)
   ...: d_out
   ...: 
Out[1]: 'strip,\x00er,er,MY\\,nr\x00,SPAC,ES\x00,!,'

      

0


source







All Articles