[Python-ideas] One way to do format and print

Sven R. Kunze srkunze at mail.de
Mon Sep 7 18:40:33 CEST 2015


On 07.09.2015 14:19, Steven D'Aprano wrote:
> I probably wouldn't use the locals() form if the variable names were
> hard-coded like that, especially for just two of them:
>
>      "Hello, I am {b}. My favorite number is {a}.".format(a=a, b=b)
>
> Where the locals() trick comes in handy is when your template string is
> not hard-coded:
>
>      if greet:
>          template = "Hello, I am {name}, and my favourite %s is {%s}."
>      else:
>          template = "My favourite %s is {%s}."
>      if condition:
>          template = template % ("number", "x")
>      else:
>          template = template % ("colour", "c")
>      print(template.format_map(locals())

Err? I rather think you wouldn't pass code review.

Best,
Sven



More information about the Python-ideas mailing list