Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape a colon in Python format() when using kwargs?

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'
like image 504
gak Avatar asked Nov 11 '13 18:11

gak


4 Answers

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'
like image 142
dawg Avatar answered Oct 22 '22 00:10

dawg


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
like image 21
Granitosaurus Avatar answered Oct 22 '22 00:10

Granitosaurus


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.

like image 10
murgatroid99 Avatar answered Oct 22 '22 01:10

murgatroid99


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
like image 2
RichieHindle Avatar answered Oct 22 '22 00:10

RichieHindle