1

我经常发现自己这样做:

myvariable = 'whatever'
another = 'something else'

print '{myvariable} {another}'.format(
    myvariable=myvariable,
    another=another
)

有没有办法不必以这种重复的方式命名关键字参数?我在想一些事情:

format_vars = [myvariable, another]

print '{myvariable} {another}'.format(format_vars)
4

2 回答 2

4

您可以使用 locals():

print '{myvariable} {another}'.format(**locals())

也可以(至少在 Cpython 中)从范围中自动选择格式变量,例如:

def f(s, *args, **kwargs):
    frame = sys._getframe(1)
    d = {}
    d.update(frame.f_globals)
    d.update(frame.f_locals)    
    d.update(kwargs)
    return Formatter().vformat(s, args, d)    

用法:

myvariable = 'whatever'
another = 'something else'

print f('{myvariable} {another}')

请参阅从其调用范围中提取变量的字符串格式化程序是不好的做法吗?有关此技术的更多详细信息。

于 2013-05-31T09:57:29.883 回答
1

当然:

>>> format_vars = {"myvariable": "whatever",
...                "another": "something else"}
>>> print('{myvariable} {another}'.format(**format_vars))
whatever something else
于 2013-05-31T09:55:31.203 回答