This question comes from handling jupyter magics
, but can be expressed in a more simple way. Given a string s = "the key is {d['key']}"
and a dictionary d = {'key': 'val'}
, we want to parse the string.
The old method would be .format()
, which will raise an error - it doesn't handle dictionary keys.
"the key is {d['key']}".format(d=d) # ERROR
I thought the only way around was to transform the dictionary to an object (explained here or here).
"the key is {d.key}".format(obj(d))
But Martijn explained nicely that you can simply leave out the quotes to get it working:
"the key is {d[key]}".format(d=d)
Still the new method f'string'
does handle dictionary keys ain an intuitive python manner:
f"the key is {d['key']}"
It also handles functions - something .format
also cannot handle.
f"this means {d['key'].lower()}"
Although we now know that you can do it with .format
, I am still wondering about the original question: given s
and d
, how do you force a f'string'
parse of s
? I added another example with a function inside the curly brackets, that .format
can also not handle and f'string'
would be able to solve.
Is there some function .fstring()
or method available? What does Python use internally?