Reputation: 113
I have a text: "{name} likes {post}". I fetch data according to the values inside {} from db. Then I get values coming inside an Array, like ["John", "515335"] for one piece of data.
I don't know how many variables I will get inside the string. Would be 1 or 3 too. ( But the count of content to be replaced and values will be same)
So what would be the best way to replace the values in this string please?
I tried:
for i in range(len(subContentArr)):
content = re.sub(subContentArr[i], valuesArr[i], content, flags=re.IGNORECASE)
But I get local variable 'content' referenced before assignment
. (Content is the text I get with curly braces)
Expected output: "John likes 515335"
Upvotes: 1
Views: 101
Reputation: 1033
If a
and b
are your inputs from your database, you can create your wanted output d
like this:
import re
a = "{name} likes {post}"
b = ['John', '515335']
c = re.sub(r'\{[^}]+\}', '{}', a)
d = c.format(*b)
Basically c
will be a modified version of your input string which will simplify the placeholders to {}
on which we then can use .format()
to replace the placeholders with the values in the same order.
Upvotes: 5