string.format(...,** locals())的缩写 [英] short form for string.format(...,**locals())
问题描述
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"
很快,代码就被X.format(**locals())
缠住了.
为了解决这个问题,我尝试创建一个lambda:
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")
但这会引发KeyError,因为locals()
是lambda的本地变量.
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"
但是这不起作用,因为python仅格式化一次. 现在,我可以编写一个重复格式化的函数,直到无所事事为止:
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?
推荐答案
f = lambda x, l=locals(): x.format(**l)
似乎可以正常工作...
f = lambda x, l=locals(): x.format(**l)
appears to work...
,如果您想要一个更全面的版本(可能会慢很多):
and if you wanted a version that is a little more all-encompassing (and probably a lot slower):
fg = lambda x, l=locals(), g=globals(): x.format(**dict(g.items() + l.items()))
将在本地或全局中找到符号.
will find the symbols in either locals or globals.
这篇关于string.format(...,** locals())的缩写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!