import re
strings = [
"hello this is an example [ a b c ]",
"hello this is another example [ cat bird dog elephant ]"
]
pattern = r"\[\s*([^][]*?)\s*]"
for s in strings:
print(re.sub(pattern, lambda m: "[{0}]".format(re.sub(r"\s+", ',', m.group(1))), s))
aW1wb3J0IHJlCgpzdHJpbmdzID0gWwogICAgImhlbGxvIHRoaXMgaXMgYW4gZXhhbXBsZSBbIGEgICAgYiBjIF0iLAogICAgImhlbGxvIHRoaXMgaXMgYW5vdGhlciBleGFtcGxlIFsgY2F0ICAgIGJpcmQgZG9nIGVsZXBoYW50ICAgXSIKXQoKcGF0dGVybiA9IHIiXFtccyooW15dW10qPylccypdIgpmb3IgcyBpbiBzdHJpbmdzOgogICAgcHJpbnQocmUuc3ViKHBhdHRlcm4sIGxhbWJkYSBtOiAiW3swfV0iLmZvcm1hdChyZS5zdWIociJccysiLCAnLCcsIG0uZ3JvdXAoMSkpKSwgcykp