[英]pprint(): how to use double quotes to display strings?
如果我使用pprint
打印字典,它總是將字符串包裹在單引號( '
)周圍:
>>> from pprint import pprint
>>> pprint({'AAA': 1, 'BBB': 2, 'CCC': 3})
{'AAA': 1, 'BBB': 2, 'CCC': 3}
有沒有辦法告訴pprint
使用雙引號( "
)?我想有以下行為:
>>> from pprint import pprint
>>> pprint({'AAA': 1, 'BBB': 2, 'CCC': 3})
{"AAA": 1, "BBB": 2, "CCC": 3}
看來您正在嘗試產生JSON; 如果是這樣,請使用json
模塊 :
>>> import json
>>> print json.dumps({'AAA': 1, 'BBB': 2, 'CCC': 3})
{"AAA": 1, "BBB": 2, "CCC": 3}
pprint()
函數生成Python表示形式 ,而不是JSON,並且引用樣式不可配置。 不要混淆這兩種語法。 乍一看,JSON看起來很像Python,但區別不只是引用樣式:
{...}
與鍵-值對的對象, [...]
數組, "..."
字符串,數字和布爾空值)。 Python數據結構要豐富得多。 true
和false
編寫。 Python使用標題大小寫True
和False
。 null
表示缺少值,Python使用None
。 \\n
和\\"
任意代碼點轉義\\xXX
,還使用\\uXXXX
16位十六進制表示法\\xXX
字符串涵蓋了所有Unicode,並且該語法支持\\xXX
, \\uXXXX
和\\UXXXXXXXX
8、16和32位轉義序列。 如果要生成縮進的JSON輸出(有點像pprint()
輸出用於列表和字典的縮進的Python語法),則在json.dumps()
調用中添加indent=4
和sort_keys=True
:
>>> print json.dumps({'AAA': 1, 'CCC': 2, 'BBB': 3}, indent=4, sort_keys=True)
{
"AAA": 1,
"BBB": 2,
"CCC": 3
}
參見http://stackoverflow.com/questions/12943819/how-to-python-prettyprint-a-json-file
我看到 OP 想要 JSON,但我不想要 JSON 並且 pprint 非常接近給我我想要的東西: black
兼容 ZA7F5F35426B927411FC9231B56382173,這需要我使用"
源”而不是“Z '
。
我選擇了.replace("'", '"')
和pformat()
,盡管這既丑陋又脆弱☹️:
import pprint
# Note: my code auto-generates my_dict parsing a file (not black-formatted here)
my_dict = ["spam", "eggs", "lumberjack", "knights", "ni", "eggs", "lumberjack", "knights", "ni"]
pprinter = pprint.PrettyPrinter(indent=4)
formatted_code = (
pprinter.pformat(my_dict)
.replace("[ ", "[\n ") # break after opening bracket
.replace("']", "',\n]") # break before closing bracket, add comma
.replace("'", '"') # use double quotes
)
with open("example_module.py", "w", encoding="utf-8") as outfile:
outfile.write('"""Module containing auto-generated ALL_MR_HEADERS."""\n')
outfile.write(f"ALL_MR_HEADERS = {formatted_code}\n")
生成的 example_module.py 符合black
標准。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.