Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing { and } with new format syntax

Tags:

python

I need to add '{' and/or '}' in a string where I use the format function to format the string. For example: I want my string to be "{3}", but this:

"\{{}\}".format(3) 

gives me the error:

ValueError: Single '}' encountered in format string 

Does anyone know how use '{' and '}' in string formatting?

Thanks, Jeremy

like image 426
jlconlin Avatar asked Jun 16 '11 15:06

jlconlin


People also ask

What is format syntax in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

What is formatted printing in Python?

To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. The str.format()method of strings help a user to get a fancier Output. User can do all the string handling by using string slicing and concatenation operations to create any layout that user wants.

What is the syntax of string formatting?

Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".

What is written by format () method?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.


2 Answers

Simply duplicate the braces:

>>> "{{{0}}}".format(3) '{3}' 
like image 124
Sven Marnach Avatar answered Sep 29 '22 16:09

Sven Marnach


print "{{{0}}}".format(3) '{3}' 
like image 45
mouad Avatar answered Sep 29 '22 15:09

mouad