Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a dictionary into a string in python

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")
like image 542
KishB87 Avatar asked May 08 '26 04:05

KishB87


1 Answers

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."
like image 51
warvariuc Avatar answered May 09 '26 17:05

warvariuc