f-string anomaly

MRAB python at mrabarnett.plus.com
Mon May 14 15:54:36 EDT 2018


On 2018-05-14 20:24, 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?
> 
You need to look at the original post for the value of 'd':

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')



More information about the Python-list mailing list