0

I have a string that a user entered s = "my name is {name} and my age is {age}" and I am trying to have {name} and {age} replaced by other strings.

In the case of a single variable name="bob", using .replace('{name}', 'bob') would be simple if it was only {name}, but I am aiming to have around 10-15 different variables, which would complicate things.

The variable could be at any position in the string, I am also getting the string from a database d = {'name': 'bob', 'age': 18}, so f-strings can't be used.

divenex
  • 15,176
  • 9
  • 55
  • 55
editid
  • 15
  • 5

1 Answers1

5

You can expand a dict into str.format().

s = "my name is {name} and my age is {age}"
d = {'name': 'bob', 'age': 18}
print(s.format(**d))  # -> my name is bob and my age is 18

Related: How do I create variable variables?

divenex
  • 15,176
  • 9
  • 55
  • 55
wjandrea
  • 28,235
  • 9
  • 60
  • 81