Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override {} placeholders in python string format method

I am trying to use python format method to do format my placeholder in a string.

The issue is the string contains {} internally and the string method is unable to resolve it.

my_value='v'
'{"k":"{value}"}'.format(value=my_value)    # This results in error due to outside {}
# Desired Output '{"k":"v"}'

How would I resolve this ?

  • I can convert this to json and then substitute but I prefer if the string format can do it
like image 788
Spandan Brahmbhatt Avatar asked Mar 17 '26 14:03

Spandan Brahmbhatt


1 Answers

You don't need to override something, you can just escape the curly brackets by doubling them, as stated in the documentation for the format string syntax:

If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

>>> '{{"k":"{value}"}}'.format(value=my_value)
'{"k":"v"}'

This equally applies for formatted string literals if you plan on using them at some point:

>>> f'{{"k": "{my_value}"}}'
'{"k": "v"}'
like image 146
Dimitris Fasarakis Hilliard Avatar answered Mar 19 '26 02:03

Dimitris Fasarakis Hilliard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!