如何格式化python对象的输出字符串

2024-03-29 12:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我得到一个嵌套了list类型元素的dict对象,并使用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代码实现?谢谢!你知道吗


Tags: noneiddefrangeallruledesccols
2条回答

我试着按照@justhalf的建议使用漂亮的印花。但是我很难做到这一点,直到我意识到我的dict太短了(少于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'}]}]

你可以使用Pretty Print

from pprint import pprint
pprint(the_dict)

相关问题 更多 >