简体   繁体   中英

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

Simply duplicate the braces:

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

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  { {'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM