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.ur...@gmail.com> > Date: February 22, 2011 2:31:08 PM PST > To: Steve Holden <st...@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~
_______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com