I usually use the following pattern (as mentioned in this question ):
a=1 s= "{a}".format(**locals())
I think this is a great way to write easy to read code.
It is sometimes useful to “chain” string formats to “modulate” the creation of complex strings:
a="1" b="2" c="{a}+{b}".format(**locals()) d="{c} is a sum".format(**locals())
Pretty soon, code is scanned using X.format(**locals()) . To solve this problem, I tried to create a lambda:
f= lambda x: x.format(**locals()) a="1" b="2" c= f("{a}+{b}") d= f("{c} is a sum")
but this raises a KeyError as locals() are lambda locales.
I also tried applying the format only to the last line:
a="1" b="2" c="{a}+{b}" d="{c} is a sum".format(**locals())
But this does not work, since python only formats once. Now I can write a function that formats several times while you have nothing more to do:
def my_format( string, vars ): f= string.format(**vars) return f if f==string else my_format(f, vars)
but I wonder: is there a better way to do this?
scope python string lambda string-formatting
goncalopp Oct 23 '13 at 18:50 2013-10-23 18:50
source share