0

When I try to run the following code

a= """{"hi":"hello "} {user}"""
a.format({"user":"xxx"})

I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '"hi"'

Please let me know how to solve this problem, I have been trying for a long time.

4
  • You are not passing a value for hi? What are you trying to acheive? Commented Feb 6, 2015 at 15:58
  • how about removing the " " from the "hi" Commented Feb 6, 2015 at 15:58
  • I cannot make any sense of your code. What do you want to achieve? From string to dictionary? Commented Feb 6, 2015 at 15:58
  • still don't understand what you want, what is a? Commented Feb 6, 2015 at 16:01

1 Answer 1

1

You need to escape the { and } and then you need to pass keyword arguments to format, not a dict

a= """{{"hi":"hello "}} {user}"""
print a.format(**{"user":"xxx"})
print a.format(user="xxx")

output

{"hi":"hello "} xxx
{"hi":"hello "} xxx

Or if you are trying to get the string representation:

a= """{{"hi":"hello "}} {user}"""
print a.format(user=str({"user":"xxx"}))

output

{"hi":"hello "} {'user': 'xxx'}
Sign up to request clarification or add additional context in comments.

2 Comments

what if a= """{"hi":{"hello ":"how"}} {user}""" and I need to print {"hi":{"hello":"how"}} xxx
You need to escape all of them, you would need to double all of the ones that aren't used for formatting. """{{"hi":{{"hello ":"how"}}}} {user}"""

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.