![](/img/trans.png)
[英]Convert list of string dictionary to another dictionary using python 2.7 and print in tabular format
[英]How to print a dictionary using string format in python
當我嘗試運行以下代碼時
a= """{"hi":"hello "} {user}"""
a.format({"user":"xxx"})
我收到此錯誤:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: '"hi"'
請讓我知道如何解決此問題,我已經嘗試了很長時間。
您需要轉義{
和}
,然后需要將關鍵字參數傳遞給format
,而不是dict
a= """{{"hi":"hello "}} {user}"""
print a.format(**{"user":"xxx"})
print a.format(user="xxx")
產量
{"hi":"hello "} xxx
{"hi":"hello "} xxx
或者,如果您嘗試獲取字符串表示形式:
a= """{{"hi":"hello "}} {user}"""
print a.format(user=str({"user":"xxx"}))
產量
{"hi":"hello "} {'user': 'xxx'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.