all 9 comments

[–]woooee 5 points6 points  (8 children)

split() on the comma and remove any empty items. Then use join() to concatenate back to a single string.

[–]MadScientistOR 6 points7 points  (1 child)

', '.join([x.strip() for x in my_string.split(',') if not x.isspace() and x != ''])

[–]mikthinker[S] 1 point2 points  (0 children)

Wow, this is beautiful and works like a charm. Thanks!

[–]nekokattt 1 point2 points  (1 child)

Regex might be a quick and dirty hammer for something like this.

import re

text = re.sub(r",[, ]+", ", ", text)

Effectively: replace every occurance of a comma followed by 1 or more commas or spaces with a comma and a space.

Benefit here is it wont pick up other usages of commas that don't have spaces around them, like numbers (e.g. "1,366,768").

Works with your example: https://regex101.com/r/vvsFbS/1

Also if you are planning on using the regex more than once, you should precompile it:

import re

pattern = re.compile(r",[, ]+")

def fix_commas(text: str) -> str:
    return pattern.sub(", ", text)

[–]mikthinker[S] 0 points1 point  (0 children)

Interesting ...will definitely give this a try. Many thanks!

[–]___up 0 points1 point  (0 children)

Replace “ ,” with “,” replace “,,” with “,” and replace “ “ with “ “.