Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re.sub replace spaces with comma

I have a list of items which look like so:

 2.4       -2.0           4.3
-6.0       12.5           1.0

What I would like is to remove all those spaces and replace them with "," (comma) except for the spaces in front of first numbers (they should be just deleted (the spaces) and not replaced with anything). So the upper string items should look like so, after replacement:

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

Not like this:

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

Which is what the following code does:

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

What regular expression for re.sub should be used to achieve that? Thank you.

like image 479
marco Avatar asked Nov 15 '14 19:11

marco


People also ask

How do you replace re subs?

If you want to replace a string that matches a regular expression (regex) instead of perfect match, use the sub() of the re module. In re. sub() , specify a regex pattern in the first argument, a new string in the second, and a string to be processed in the third.

How do you remove spaces and commas in python?

sub() function to erase commas from the python string. The function re. sub() is used to swap the substring. Also, it will replace any match with the other parameter, in this case, the null string, eliminating all commas from the string.

How do I remove commas from a list in python?

You can remove comma from string in python by using string's replace() method.


1 Answers

To remove the leading and trailing spaces you can use .strip(), and then to replace consecutive whitespace characters using the regular expression \s+:

>>> import re
>>> s = " 2.4       -2.0           4.3"
>>> re.sub("\s+", ",", s.strip())
'2.4,-2.0,4.3'
like image 85
DanielGibbs Avatar answered Oct 07 '22 05:10

DanielGibbs