Skip to content Skip to sidebar Skip to footer

What Are Valid Keys According To Python Str.format() Documentation

I'm new to Python and just read the following part from Python doc 6.1.3. Format String Syntax: Because arg_name is not quote-delimited, it is not possible to specify arbitrary dic

Solution 1:

I think I know the answer after reading and thinking more. Thanks to @decimus phostle in that post which mentioned the PEP. There is a nearly same statement that finally answered my question:

Because **keys** are not quote-delimited, it isnot possible to
specify arbitrary dictionary keys (e.g., the strings "10"or":-]") from within a format string.

The difference is that it says keys not arg_name in the PEP. So "not quote-delimited" means quotes are ordinary characters in a key. For example,

{0["1"]}

In this replacement field, the key is three characters: double quote, 1, and double quote, not one character 1. So obviously there is no such three-character key in the dictionary.

Also accoring to the PEP, it has simple rule to find key: if it starts with a digit, then it is a number; otherwise it is a string. This means that if your dictionary has a key of string, but consist of digit character, for example, '10', there is no way you can specify the key in replacement field. Because if you use 10 in replacment field, it is considered number 10; If you use '10', it is considered string of four characters, not a string of two character '1' and '0'.

For ':-]' as key, why it is not possible? Because quotes are not delimiters,

{0[':-]']}

the quotes won't make the inner ] quoted (literal). So it becomes the matched ] of [, which terminates the index prematurely.

Here is a valid key in a replacement field to compare:

dd = {"'10'":'a'}    
print("{0['10']}".format(dd))

To use something like '10' as key in the replacement field, you need to make sure the dictionary has a key named "'10'".

Post a Comment for "What Are Valid Keys According To Python Str.format() Documentation"