How can I print literal curly-brace characters in python string and also use .format on it?


Question

x = " \{ Hello \} {0} "
print x.format(42)

gives me : Key Error: Hello\\

I want to print the output: {Hello} 42

1
1245
9/20/2017 6:56:23 PM

Accepted Answer

You need to double the {{ and }}:

>>> x = " {{ Hello }} {0} "
>>> print x.format(42)
' { Hello } 42 '

Here's the relevant part of the Python documentation for format string syntax:

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

1711
3/29/2011 12:08:55 AM

You escape it by doubling the braces.

Eg:

x = "{{ Hello }} {0}"
print x.format(42)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon