3

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")

4 Answers 4

5

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."
Sign up to request clarification or add additional context in comments.

Comments

0
def sub_m(name, nickname)
    print "I'm %s. My real name is %s, but my friends call me %s" % (name, nickname, name)

Comments

0

I don't think you're creating the dictionary the way you think you are. the %(name) and %(nickname) placeholders must refer to a valid key in the dictionary you pass. Thus, you need something like:

'the quick brown %(animal)s jumped over the %(adjective)s dog' % {"animal": "fox", "adjective": "lazy"}

What you have is a dictionary with a key "Mike" and a value of "Goose". If you changed %(name)s and %(nickname)s in your original string to %(Mike)s, you'd get Goose substituted 3 times.

Comments

0

You can simply use positional parameters, like this:

given_string2 = "I'm {0}. My real name is {1}, but my friends call me {0}."
def sub_m(name, nickname):
    return given_string2.format(name, nickname)
print sub_m("Mike","Goose")

The {} formatters refer to the 0-indexed positional arguments of the format() method applied to the string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.