f-string anomaly

Ken Kundert theNurd at nurdletech.com
Mon May 14 17:33:23 EDT 2018


Lele,
    I am using Python3.6. d has to be an object of mydict.

Here is the code that exhibits the problem:

     import sys, os
     from inform import error, os_error

     class mydict(dict):
         def __format__(self, template):
             print('Template:', template)
             return ', '.join(template.format(v, k=k, v=v) for k, v in
self.items())


     d = mydict(bob='239-8402', ted='371-8567', carol='891-5810',
alice='552-2219')

     print('Using format():')
     print('Email: {0:{{k}}: {{v}}}'.format(d))
     print()
     print('Using f-string:')
     print(f'Email: {d:{{k}} {{v}}}')
     print()
     print('Using f-string:')
     k=6
     v=9
     print(f'Email: {d:{{k}} {{v}}}')

The result is:

    NameError: name 'k' is not defined

-Ken





On 05/14/2018 12:24 PM, Lele Gaifax wrote:
> Ken Kundert <theNurd at nurdletech.com> writes:
> 
>> Lele,
>>     I'm afraid I was unclear. The ... in the code snippet was intended
>> to imply that these lines were appended to the end of the original code,
>> where d was defined.
> 
> Ok, but then I get a different behaviour:
> 
>     Python 3.6.5 (default, May 11 2018, 13:30:17) 
>     [GCC 7.3.0] on linux
>     Type "help", "copyright", "credits" or "license" for more information.
>     >>> k=1
>     >>> v=2
>     >>> d=3
>     >>> print(f'Email: {d:{{k}} {{v}}}')
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in <module>
>     ValueError: Invalid format specifier
> 
> Which Python version are you using?
> 
> ciao, lele.
> 




More information about the Python-list mailing list