W3docs

How do I print curly-brace characters in a string while using .format?

To print a curly brace character in a string that is being formatted with the .format() method, you will need to use double curly braces to escape the character.

To print a curly brace character in a string that is being formatted with the .format() method, you will need to use double curly braces to escape the character. In Python's format mini-language, `{{` and `}}` act as escape sequences that render as literal { and } respectively. For example:

Print curly-brace characters in a string while using format method in Python

formatted_string = "The value is: {{This is a string with curly braces}}".format()
print(formatted_string)

This will print The value is: {This is a string with curly braces}.

Alternatively, you can use the % operator to format the string, like this:

Print curly-brace characters in a string while using % operator

string = "{This is a string with curly braces}"
formatted_string = "The value is: %s" % string
print(formatted_string)

This will also print The value is: {This is a string with curly braces}. Note that the % operator does not require escaping curly braces, as it treats the substituted string as literal text rather than parsing a format mini-language. (Note: % string formatting is considered legacy in modern Python.) For modern Python code, f-strings (f'...') are generally preferred over .format().