2013-12-19 214 views
4

使用上的繩子.format時,我有一個字符串,我想用.format蟒功能,在其上添加運行一些變數,這是我的字符串:KeyError異常在Python

'{"auth": {"tenantName": "{Insert String Here}", "passwordCredentials": {"username": "{insert String here}", "password": "{insert String Here}"}}}' 

當我使用.format這樣的:

credentials='{"auth": {"tenantName": "{tenant}", "passwordCredentials": {"username": "{admin}", "password": "{password}"}}}'.format(tenant='me',admin='test',password='123') 

它給了我下面的錯誤:

KeyError: '"auth"' 

任何幫助?提前致謝。

+0

你可以把你完整的代碼在這裏? – 2013-12-19 04:16:11

+2

您需要轉義額外的'{'s –

+0

這是迄今爲止的完整代碼。我只需要調整我指定的3個字符串。 – mobykhn

回答

11

{}是字符串格式的特殊字符,因爲你清楚地知道,因爲你正在使用他們的{tenant}{admin}{password} 。所有其他{ s和}都需要通過加倍來逃脫。嘗試:

credentials='{{"auth": {{"tenantName": "{tenant}", "passwordCredentials": {{"username": "{admin}", "password": "{password}"}}}}}}'.format(tenant='me',admin='test',password='123') 
+0

感謝這工作 – mobykhn

-1

我認爲大括號可能會殺死你。如果您使用的是格式,則希望{}內的內容成爲密鑰。也就是說,我不認爲你可以在包含非格式化的{{}}的字符串中使用.format,因爲它不知道如何解析它。但是,你可以這樣做:

credentials='["auth": ["tenantName": "{tenant}", "passwordCredentials": ["username": "{admin}", "password": "{password}"]]}'.format(tenant='me',admin='test',password='123') 

然後做一個

credentials.replace("[","{") 
credentials.replace("]","}") 
+0

這並不理想。看文檔:http://docs.python.org/2/library/string.html#formatstrings –

+0

事實上,這隻會造成浩劫。 – Iguananaut

0

.format函數窒礙了你的額外{}括號。它正在尋找這些大括號作爲搜索和替換內容的指示,所以當它看到這些大括號時,它認爲它正在尋找替代的關鍵。

您需要轉義不意味着指示鍵的大括號。對於.format,這是通過加倍大括號完成的。所以,你的代碼應該是這樣的:

credentials='{{"auth": {{"tenantName": "{tenant}", "passwordCredentials": {{"username": "{admin}", "password": "{password}"}}}}}}'.format(tenant='me',admin='test',password='123') 

請參閱該文檔:http://docs.python.org/2/library/string.html#formatstrings

也看到了這個問題: How can I print literal curly-brace characters in python string and also use .format on it?

+0

@BurhanKhalid它不需要代碼,這顯然是一個固定的json數據結構。 –

0

你的字符串開頭{"auth"。只要格式字符串解析器看到該開放大括號,就認爲"auth"是傳遞給.format()的格式變量的名稱。您需要使用雙捲曲線將模板字符串中的花括號轉義出來,如{{

這就是說,它看起來像你試圖建立一個JSON字符串。只需使用json模塊即可。

4

您正在使用錯誤的工具進行交易。您正在處理json,你需要使用JSON庫解析數據,然後訪問您的字段作爲字典

>>> import json 
>>> data_dict = json.loads(data) 
>>> data_dict["auth"]["tenantName"] 
u'{Insert String Here}' 
+0

很好的解決方法。 – Kracekumar