re.sub replace spaces with comma
Question:
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.
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'
There are many solutions… This doesn’t even briefly cover the whole topic, but it works:
Quick solution:
In [1]: import re
...: d_in = "strip trnx00er terrMY nrx00 trnSPAC ESx00 ! "
...: d_out = re.sub("s+", r",", d_in)
...: d_out
...:
Out[1]: 'strip,x00er,er,MY\,nrx00,SPAC,ESx00,!,'
my_string = "1 2 3"
my_string_2 = my_string.replace(' ', ';')
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.
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'
There are many solutions… This doesn’t even briefly cover the whole topic, but it works:
Quick solution:
In [1]: import re
...: d_in = "strip trnx00er terrMY nrx00 trnSPAC ESx00 ! "
...: d_out = re.sub("s+", r",", d_in)
...: d_out
...:
Out[1]: 'strip,x00er,er,MY\,nrx00,SPAC,ESx00,!,'
my_string = "1 2 3"
my_string_2 = my_string.replace(' ', ';')