簡體   English   中英

如何格式化python對象的輸出字符串

[英]how to pretty-format an output string of a python object

如果我有一個嵌套的類型為dict元素的list對象,並使用print命令將列表打印出來。 輸出可能會像這樣, 全部壓在一起

[{'rule_range': u'ALL', 'rule_desc': u'\u6d4b\u8bd5\u89c4\u5219\u5b9e\u4f8b01', 'creator': u'65624', 'rule_tmpl_id': u'RT0001', 'order_id': u'1', 'id': 2L, 'def_ext_cols': None, 'rule_cycle': u'1', 'create_time': None, 'rule_expr': u'select * from records where year = 2000', 'def_cols': None, 'rule_status': u'1', 'rule_id': u'TEST0001', 'store': None, 'rule_name': u'TRuleInstance01'}, {'rule_range': u'ALL', 'rule_desc': u'\u6d4b\u8bd5\u89c4\u5219\u5b9e\u4f8b01', 'creator': u'65624', 'rule_tmpl_id': u'RT0001', 'order_id': u'2', 'id': 2L, 'def_ext_cols': None, 'rule_cycle': u'1', 'create_time': None, 'rule_expr': u'select * from records where temperature = 21', 'def_cols': None, 'rule_status': u'1', 'rule_id': u'TEST0001', 'store': None, 'rule_name': u'TRuleInstance01'}]

我想要的是一些格式化的輸出字符串 ,是否有某種格式化程序(就像json在線格式化程序一樣),或者可以在python代碼中實現? 非常感謝!

您可以使用Pretty Print

from pprint import pprint
pprint(the_dict)

我嘗試按照@justhalf的建議使用Pretty Print。 但是我很難完成這項工作,直到我意識到我的字典太短了(少於80個字符,這是pprint的默認寬度)。 我將寬度更改為20,現在可以正確打印:

import pprint
pprint.pprint([{"test":"value", "test2":"value"},{"test":[{"key":"value"}]}])

印刷品:

[{   'test': 'value', 'test2': 'value'}, {   'test': [{   'key': 'value'}]}]

但:

import pprint
pprint.pprint([{"test":"value", "test2":"value"},{"test":[{"key":"value"}]}], width=20)

印刷品:

[{'test': 'value',
  'test2': 'value'},
 {'test': [{'key': 'value'}]}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM