fork download
  1. import re
  2. list_words = ["cat", "dog", "animals", "adam"]
  3. text = "I have a lot of animals, cat and a dog"
  4. pattern = r",*(\s*\b(?:{}))\b".format("|".join(list_words))
  5. print( re.sub(pattern, r",\1", text) )
  6.  
Success #stdin #stdout 0.03s 9764KB
stdin
Standard input is empty
stdout
I have a lot of, animals,       cat and a,     dog