I'm running the following code:
asset = {}
asset['abc'] = 'def'
print type(asset)
print asset['abc']
query = '{"abc": "{abc}"}'.format(abc=asset['abc'])
print query
Which throws a KeyError
error:
[user@localhost] : ~/Documents/vision/inputs/perma_sniff $ python ~/test.py
<type 'dict'>
def
Traceback (most recent call last):
File "/home/user/test.py", line 5, in <module>
query = '\{"abc": "{abc}"\}'.format(abc=asset['abc'])
KeyError: '"abc"'
Format is obviously getting confused by the wrapping {
. How can I make sure format only tries to replace the (correct) inner {abc}
.
ie, expected output is:
{"abc": "def"}
(I'm aware I could use the json
module for this task, but I want to avoid that. I would much rather use format.)
To escape curly braces and interpolate a string inside the String. format() method use triple curly braces {{{ }}} . Similarly, you can also use the c# string interpolation feature instead of String.
If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }} . So if you want to print "{42}", you'd use "{{{0}}}". format(42) !
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}.
Python f-string escaping characters To escape a curly bracket, we double the character. A single quote is escaped with a backslash character.
Multiple pairs of curly braces can be used while formatting the string. Let’s say if another variable substitution is needed in the sentence, can be done by adding a second pair of curly braces and passing a second value into the method. Python will replace the placeholders with values in order. Syntax : { } { }.format (value1, value2)
Your string begins with {"auth". As soon as the format string parser sees that opening curly brace it thinks that "auth"is the name of a format variable as passed in to .format(). You need to escape any curly braces in your template string with double curly_braces, like {{.
The curly brackets are valid as the definition of a single element constant-array, but should not be required unless you are performing multiple tests simultaneously. What version of Excel are you using?
2 Django-tables2 KeyError when field has {curly brackets} 0 Unable to fetch rows from PostGresSQL table 1 format string inside curly brackets are replaced with one curly brackets
To insert a literal brace, double it up:
query = '{{"abc": "{abc}"}}'.format(abc=asset['abc'])
(This is documented here, but not highlighted particularly obviously).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With