2014-05-02 18 views
1

在沒有創建新變量的情況下在使用** locals()的.format()中使用它之前,是否可以操作局部變量?所以,這樣的效果與此相同:在Python中插入格式(** 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) 

但它拋出一個錯誤「語法錯誤:無效的語法」在第一個逗號後的當地人()。

回答

1

只要改變順序:

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) 

地方(和全球)變量會自動傳入,表達式使用數字佔位符。