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

ID : 455

viewed : 97

Tags : pythonstringformatstring-formattingcurly-bracespython

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

vote vote

98

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

vote vote

88

Python 3.6+ (2017)

In the recent versions of Python one would use f-strings (see also PEP498).

With f-strings one should use double {{ or }}

n = 42   print(f" {{Hello}} {n} ") 

produces the desired

 {Hello} 42 

If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:

hello = "HELLO" print(f"{{{hello.lower()}}}") 

produces

{hello} 
vote vote

80

You escape it by doubling the braces.

Eg:

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

67

The OP wrote this comment:

I was trying to format a small JSON for some purposes, like this: '{"all": false, "selected": "{}"}'.format(data) to get something like {"all": false, "selected": "1,2"}

It's pretty common that the "escaping braces" issue comes up when dealing with JSON.

I suggest doing this:

import json data = "1,2" mydict = {"all": "false", "selected": data} json.dumps(mydict) 

It's cleaner than the alternative, which is:

'{{"all": false, "selected": "{}"}}'.format(data) 

Using the json library is definitely preferable when the JSON string gets more complicated than the example.

vote vote

55

Try this:

x = "{{ Hello }} {0}"

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

Related QUESTION?