Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

gives me : Key Error: Hello\\

I want to print the output: {Hello} 42

like image 948
Schitti Avatar asked Mar 29 '11 00:03

Schitti


People also ask

How do you use curly braces in string format?

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.

Can you use {} in Python?

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.

How do you escape braces in string format?

You need to use quadruple brackets to escape the string interpolation parsing and string.

How do you match curly braces in regex Python?

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


2 Answers

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

like image 196
Greg Hewgill Avatar answered Sep 29 '22 22:09

Greg Hewgill


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} 
like image 23
divenex Avatar answered Sep 29 '22 22:09

divenex