在python中使用格式(**locals())插入值之前对其进行操作
在.format()中将局部变量与**locals()一起使用之前,是否可以在不生成新变量的情况下对其进行操作?因此,有一些与此相同的效果:在python中使用格式(**locals())插入值之前对其进行操作,python,format,locals,Python,Format,Locals,在.format()中将局部变量与**locals()一起使用之前,是否可以在不生成新变量的情况下对其进行操作?因此,有一些与此相同的效果: medium="image" size_name="double" width=200 height=100 width2=width*2 height2=height*2 print "A {size_name} sized {medium} is {width2} by {height2}".format(**locals()) 但是更加优雅,不需要
medium="image"
size_name="double"
width=200
height=100
width2=width*2
height2=height*2
print "A {size_name} sized {medium} is {width2} by {height2}".format(**locals())
但是更加优雅,不需要创建width2和height2变量。我试过这个:
medium="image"
size_name="double"
width=200
height=100
print "A {size_name} sized {medium} is {width2} by {height2}".format(**locals(),height2=height*2,width2=width*2)
但是它在locals()之后的第一个逗号处抛出一个错误“SyntaxError:invalid syntax”。只需更改顺序:
print "A {size_name} sized {medium} is {width2} by {height2}".format(height2=height*2,width2=width*2,**locals())
明星争论总是在正常争论之后
为了让这个答案不那么琐碎,以下是我的标准曲目:
import string
def f(s, *args, **kwargs):
"""Kinda "variable interpolation". NB: cpython-specific!"""
frame = sys._getframe(1)
d = {}
d.update(frame.f_globals)
d.update(frame.f_locals)
d.update(kwargs)
return string.Formatter().vformat(s, args, d)
它可以应用于您的示例,如下所示:
print f("A {size_name} sized {medium} is {0} by {1}", width*2, height*2)
本地(和全局)变量自动传入,表达式使用数字占位符