fork download
  1. import re
  2.  
  3. strings = [
  4. "hello this is an example [ a b c ]",
  5. "hello this is another example [ cat bird dog elephant ]"
  6. ]
  7.  
  8. pattern = r"\[\s*([^][]*?)\s*]"
  9. for s in strings:
  10. print(re.sub(pattern, lambda m: "[{0}]".format(re.sub(r"\s+", ',', m.group(1))), s))
Success #stdin #stdout 0.03s 9432KB
stdin
Standard input is empty
stdout
hello this is an example [a,b,c]
hello this is another example [cat,bird,dog,elephant]