I usually use the following pattern (as mentioned in this question):
a=1
s= "{a}".format(**locals())
I think it's a great way to write easily readable code.
Sometimes it's useful to "chain" string formats, in order to "modularize" the creation of complex strings:
a="1"
b="2"
c="{a}+{b}".format(**locals())
d="{c} is a sum".format(**locals())
#d=="1+2 is a sum"
Pretty soon, the code is pestered with 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 throws a KeyError, since locals()
are the lambda's locals.
I also tried to apply the format only on the last string:
a="1"
b="2"
c="{a}+{b}"
d="{c} is a sum".format(**locals())
#d=="{a}+{b} is a sum"
But this doesn't work, since python only formats once. Now, I could write a function that formats repeatedly until there's 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'm wondering: is there a better way to do this?