I have a dictionary with a colon in a key that I wish to print. Unfortunately the colon character is used for formatting, so I need to somehow escape it.
For example:
>>> d = {'hello': 'world', 'with:colon': 'moo'}
>>> '{hello}'.format(**d)
'world'
>>> '{with:colon}'.format(**d)
KeyError: 'with'
>>> '{with\:colon}'.format(**d)
KeyError: 'with\\'
>>> '{with::colon}'.format(**d)
KeyError: 'with'
As a workaround:
>>> d = {'hello': 'world', 'with:colon': 'moo'}
>>> '{hello} {}'.format(d['with:colon'],**d)
'world moo'
>>> '{hello} {0}'.format(d['with:colon'],**d)
'world moo'
As of python 3.6 you can solve this with the new f-string formating:
>>> d = {'hello': 'world', 'with:colon': 'moo'}
>>> print(f"with:colon is equal to {d['with:colon']}")
with:colon is equal to moo
According to the documentation, what you are asking is simply not possible. Specifically,
Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings
'10'
or':-]'
) within a format string.
You can't - the keys must be syntactically equivalent to Python identifiers. See Format String Syntax in the documentation:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | integer]
attribute_name ::= identifier
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