2017-07-18 50 views
0

我想創建一個字符串,我想同時替換全局和局部變量。下面的代碼給我一個錯誤。 (KeyError異常: '表')如何在python中的字符串中插入全局和局部變量

TABLE = my_table 
def get_data(): 
    data_size = 10 
    print "get %(data_size)s rows from the table %(TABLE)s" %locals() %globals() 

我想要的代碼打印以下:

get 10 rows from the table my_table 

有誰知道如何實現這一目標?提前致謝!

+0

'print「從表%s」%(data_size,TABLE)'中獲取%s行' – khelwood

+0

@cᴏʟᴅsᴘᴇᴇᴅ它不適用於我。我得到 'TypeError:格式需要映射' –

+0

@PulkitBansal是的,我的壞。語法並不完美,但它是沿着這些線條的。看到我的答案。 –

回答

1

如果你想用你的格式化字符串完全按照你現在的樣子,你需要指定確切映射,像這樣一本字典:

mapping = {'data_size' : locals()['data_size'], 'TABLE' : globals()['TABLE']} 

,或者更簡單,

mapping = {'data_size' : data_size, 'TABLE' : TABLE} 

現在,通過映射到像這樣的字符串:

print "get %(data_size)s rows from the table %(TABLE)s" % mapping 

這會給你get 10 rows from the table my_table

您收到的TypeError是因爲%(...)s需要以傳遞給字符串的格式args指定的key:value映射。

+0

'locals()['data_size']'和'globals()['TABLE']'可以寫成'data_size'和'TABLE' – khelwood

+0

@khelwood Thanks,edited。首先應該保持這一點,因爲它似乎與OP使用locals()/ globals()的目標是同義的。 –

+0

謝謝@COLDSPEED,這很有幫助。我沒有意識到locals()和globals()基本上是字典。 –

0

您需要打印像這樣:

TABLE = "my_table" 
def get_data(): 
    data_size = 10 
    print "get %s rows from the table %s"%(data_size, TABLE) 

OUTPUT:

get 10 rows from the table my_table

+0

這是一個有用的答案。仍然有什麼方法可以在字符串中寫入變量名稱data_size和TABLE?因爲隨着字符串變長和複雜化,變得難以按照正確的順序排列。 –