[Python-Dev] Fwd: deep question re dict as formatting input
Steve Holden
steve at holdenweb.com
Wed Feb 23 00:01:06 CET 2011
One of the students on an introductory Python 3 class asks a very good question about string formatting. This could be because the course materials are misleading, so I would like to understand. It would appear from tests that "{0[X]}".format(...) first tries to convert the string "X" to in integer. If it succeeds then __getitem__() is called with the integer as an argument, otherwise it is called with the string itself as an argument. Is this correct?
The documentation at http://docs.python.org/library/string.html#formatspec is silent on whether strings were ever intended to be used as subscripts. Does this seem sensible? Was it considered during design? Should I alter the materials so that only integer subscripts are used?
regards
Steve
Begin forwarded message:
> From: kirby urner <kirby.urner at gmail.com>
> Date: February 22, 2011 2:31:08 PM PST
> To: Steve Holden <steve at holdenweb.com>
> Subject: deep question re dict as formatting input
>
>>>> d
> {'Steve': 'Holden', 'Tim': 'Peters', 'Guido': 'van Rossum', '1':
> 'string', 1: 'integer'}
>>>> "{0[Guido]} is cool".format(d)
> 'van Rossum is cool'
>>>> "{0[1]} is cool".format(d)
> 'integer is cool'
>>>> "{0['1']} is cool".format(d)
> Traceback (most recent call last):
> File "<pyshell#19>", line 1, in <module>
> "{0['1']} is cool".format(d)
> KeyError: "'1'"
>
>
> Student question:
>
> Good morning!
>
> Question on .format(), interactive session follows:
>
> --> d = {"Steve": "Holden",
> ... "Guido": "van Rossum",
> ... "Tim": "Peters",
> ... "1": "string",
> ... 1: "integer"}
>
> --> d
> {'Steve': 'Holden', 'Tim': 'Peters', '1': 'string', 1: 'integer',
> 'Guido': 'van Rossum'}
>
> --> d[1]
> 'integer'
>
> --> d['1']
> 'string'
>
> --> "{dct[1]}".format(dct=d)
> 'integer'
>
> --> "{dct[Guido]}".format(dct=d)
> 'van Rossum'
>
> --> "{dct['1']}".format(dct=d)
> Traceback (most recent call last):
> File "<console>", line 1, in <module>
> KeyError: "'1'"
>
> Question: If {dct[Guido]} treats Guido as str, why doesn't {dct[1]}
> treate 1 as str? Feels like an automatic conversion from str to int.
> Furthermore, how does one access the key '1' in a format statement?
>
> ~Ethan~
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20110222/7a53741f/attachment.html>
More information about the Python-Dev
mailing list