Given the following:
String: "{Dog} loves {Cat}",
RegExp: {([^}]+)},
Array: ["Scooby Doo", "Sylvester"]
How can I easily achieve: "Scooby Doo loves Sylvester"
You may replace each substring inside curly braces with a {} substring that acts as a placeholder when the string is passed to str.format method. The list needs to be "cast" to a sequence of variables (it is called unpacking), thus, the prefix operator * is required before the list passed to str.format.
So, the code can look like
import re
s = "{Dog} loves {Cat}"
l = ["Scooby Doo", "Sylvester"]
print(re.sub(r'{[^{}]*}', '{}', s).format(*l))
# => Scooby Doo loves Sylvester
See the Python demo.
re.sub(r'{[^{}]*}', '{}', s).format(*l)(demo)?{}and then using string replacing in python 3 style. Pretty nice trick!