3

I need to print out a string that contains ${} with format() method

For example, I'd like to print out

"hello ${a} hello"

using this python code

print "{string1} ${a} {string1}".format(string1="hello")

However, I get KeyError'a', as format() expects an input string for {a}. How can I teach format() to ignore ${a}?

1 Answer 1

3

You need to double the { and } to {{ to }}:

print "{string1} ${{a}} {string1}".format(string1="hello")
Sign up to request clarification or add additional context in comments.

1 Comment

This works well when you want to print an equal number of open and close curly braces, but python chokes on it if you only want to print an a single open brace. '{{{}}' does not work. In this case I just added the single curly brace as an additional parameter to my .format() and injected into the string that way.

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.