Skip to content
Advertisement

How to include the symbol “{” in a Python format string?

How can I include { symbol in a string?

My string

str2="call_function(Macro, {0});n { t int n;n".format("value")

I’m getting the error:

ValueError: unmatched '{' in format

I have escaped the { symbol and have tried without escaping too. I’m getting the same error in both cases.

Advertisement

Answer

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


In [1]: '{{{0}'.format('foo')
Out[1]: '{foo'
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement