![](/img/trans.png)
[英]How do I use Python's pprint module to pretty print out dictionary key value pairs nested with in a list?
[英]How do I get python's pprint to return a string instead of printing?
換句話說,相當於 pprint 的 sprintf 是什么?
pprint模塊有一個名為pformat的命令,就是為了這個目的。
從文檔:
以字符串形式返回對象的格式化表示。 縮進、寬度和深度將作為格式參數傳遞給 PrettyPrinter 構造函數。
例子:
>>> import pprint
>>> people = [
... {"first": "Brian", "last": "Kernighan"},
... {"first": "Dennis", "last": "Richie"},
... ]
>>> pprint.pformat(people, indent=4)
"[ { 'first': 'Brian', 'last': 'Kernighan'},\n { 'first': 'Dennis', 'last': 'Richie'}]"
假設你真的意味着pprint
從漂亮地打印庫,那么你想要的pprint.pformat
方法。
如果你只是想print
,那么你想要str()
>>> import pprint
>>> pprint.pformat({'key1':'val1', 'key2':[1,2]})
"{'key1': 'val1', 'key2': [1, 2]}"
>>>
您在尋找pprint.pformat
嗎?
像這樣的東西:
import pprint, StringIO
s = StringIO.StringIO()
pprint.pprint(some_object, s)
print s.getvalue() # displays the string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.