2011-02-15 90 views
4

一個在Python的最好的工具是locals()在字符串格式化:的Python:使用locals()打印字典值

>>> st="asdasd" 
>>> print "%(st)s" % locals() 
asdasd 

但是,這不能與字典中的值來完成:

>>> d={1:2, 3:4} 
>>> print "%(d[1])s" % locals() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
KeyError: 'd[1]' 

任何想法如何使這項工作?

+0

工作我不知道我得到的語法糖類比`locals`。謹慎澄清? – 2011-02-15 13:41:37

+1

``%(鍵)s「%d`?請注意,只有字符串鍵可以這種方式使用。 – ulidtko 2011-02-15 13:41:54

回答

6
>>> d={1:2, 3:4} 
>>> print '{0[1]}'.format(d) 
2 
>>> print '{0[d][1]}'.format(locals()) 
2 
>>> print '{[d][1]}'.format(locals()) 
2 
>>> 

最後一個只有2.7