本文介紹了格式:在字符串中使用大括號時出現(xiàn) KeyError的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在運行以下代碼:
asset = {}
asset['abc'] = 'def'
print type(asset)
print asset['abc']
query = '{"abc": "{abc}"}'.format(abc=asset['abc'])
print query
這會引發(fā) KeyError
錯誤:
[user@localhost] : ~/Documents/vision/inputs/perma_sniff $ python ~/test.py
<type 'dict'>
def
Traceback (most recent call last):
File "/home/user/test.py", line 5, in <module>
query = '{"abc": "{abc}"}'.format(abc=asset['abc'])
KeyError: '"abc"'
格式顯然被包裝 {
弄糊涂了.如何確保格式僅嘗試替換(正確的)內(nèi)部 {abc}
.
Format is obviously getting confused by the wrapping {
. How can I make sure format only tries to replace the (correct) inner {abc}
.
即,預(yù)期的輸出是:
{"abc": "def"}
(我知道我可以使用 json
模塊來完成這項任務(wù),但我想避免這種情況.我更愿意使用格式.)
(I'm aware I could use the json
module for this task, but I want to avoid that. I would much rather use format.)
推薦答案
要插入文字大括號,請將其加倍:
To insert a literal brace, double it up:
query = '{{"abc": "{abc}"}}'.format(abc=asset['abc'])
(在此處進行了記錄,但沒有特別明顯地突出顯示).
(This is documented here, but not highlighted particularly obviously).
這篇關(guān)于格式:在字符串中使用大括號時出現(xiàn) KeyError的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!