Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace multiple comma/space instances in a string, Python

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 ,.

like image 680
Oleg Melnikov Avatar asked Dec 19 '22 21:12

Oleg Melnikov


1 Answers

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
like image 113
Dušan Maďar Avatar answered Dec 22 '22 00:12

Dušan Maďar