I have a string with multiple successive instances of ,
(comma+space) that I want to replace with a single instance. Is there a clean way to do so? I suppose RegEx can be helpful.
A naive example:
s = 'a, b, , c, , , d, , , e, , , , , , , f
The desired output:
'a, b, c, d, e, f
Naturally, the text can change, so the search should be for successive instances of ,
.
So the regular expression searches for two or more instances of ,
(comma + space) and then in sub
function you replace it with only a single ,
.
import re
pattern = re.compile(r'(,\s){2,}')
test_string = 'a, b, , c, , , d, , , e, , , , , , , f'
print re.sub(pattern, ', ', test_string)
>>> a, b, c, d, e, f
and without a regular expression (as @Casimir et Hippolyte suggested in comment)
test_string = 'a, b, , c, , , d, , , e, , , , , , , f'
test_string_parts = test_string.split(',')
test_string_parts = [part.strip() for part in test_string_parts if part != ' ']
print ', '.join(test_string_parts)
>>> a, b, c, d, e, f
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With