HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

How do I escape curly-brace ({}) characters characters in a string while using .format?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
whilehowbraceusingcurlyescapecharactersformatstring

Problem

Non-working example:

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


Desired output:
{Hello} 42

Solution

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 }}.

Code Snippets

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

Context

Stack Overflow Q#5466451, score: 3563

Revisions (0)

No revisions yet.