I'm trying to format a string using key-value pairs where the variable modifier in the string is referenced by the name of the key.
How would I go about this? Here is my code:
given_string2 = "I'm %(name)s. My real name is %(nickname)s, but my friends call me %(name)s."
def sub_m(name, nickname):
return given_string2 %{name:nickname}
print sub_m("Mike","Goose")
Your problem is here: given_string2 % {name: nickname}
This works:
>>> "I'm %(name)s. My real name is %(nickname)s, but my friends call me %(name)s." % {'name': "Mike", 'nickname': "Goose"}
"I'm Mike. My real name is Goose, but my friends call me Mike."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With