x = " \{ Hello \} {0} " print(x.format(42))
gives me : Key Error: Hello\\
I want to print the output: {Hello} 42
To escape curly braces and interpolate a string inside the String. format() method use triple curly braces {{{ }}} . Similarly, you can also use the c# string interpolation feature instead of String.
In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.
You need to use quadruple brackets to escape the string interpolation parsing and string.
"Curly braces can be used to represent the number of repetitions between two numbers. The regex {x,y} means "between x and y repetitions of something".
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}}
.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With