I have the following string interpolation:
>>> a = {'test1.1': 5}
>>> 'test: {test1.1}'.format(**a)
KeyError: 'test1'
It obviously fails because format is literally trying to access the object test1
and its attribute 1
. Is there a way to format this string and force the key values to be taken as strings? (Looking for a Python 2 and 3 solution.)
A little hack, but this does the trick:
In [5]: 'test: {0[test1.1]}'.format(a)
Out[5]: 'test: 5'
Use dict-like indexing with [..]
. The 0
is positional indexing, and a
is the 0th argument. If it's the only argument, you can omit 0
.
Just another alternative. The old %-style formatting doesn't care:
>>> a = {'test1.1': 5}
>>> 'test: %(test1.1)s' % a
'test: 5'
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