jlconlin
jlconlin

Reputation: 15054

Printing { and } with new format syntax

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

Upvotes: 26

Views: 14761

Answers (3)

Dave X
Dave X

Reputation: 5137

If you need unmatched brackets you could use something like:

>>> " {c}{x}{o}{o}".format(o='{',c='}', x=3)
' }3{{' 

The doubling works for unmatched braces as well:

>>> "}} {} {{ {{".format(3)
'} 3  { {'

Upvotes: 6

Sven Marnach
Sven Marnach

Reputation: 601599

Simply duplicate the braces:

>>> "{{{0}}}".format(3)
'{3}'

Upvotes: 39

mouad
mouad

Reputation: 70031

print "{{{0}}}".format(3)
'{3}'

Upvotes: 6

Related Questions