首页 > 编程语言 >Pretty-print with pprint in Python

Pretty-print with pprint in Python

时间:2023-03-13 16:33:25浏览次数:43  
标签:20 Name Python Age pprint width Points print

转载自 note.nkmk.me-Pretty-print with pprint in Python

In python, you can pretty-print objects such as lists list and dictionaries dict with pprint module.

This article describes the following contents.

  • Basic usage of pprint
  • Specify the output width (number of characters): width
  • Specify the output depth: depth
  • Specify the indent width: indent
  • Reduce line breaks: compact
  • Convert to string: pprint.pformat()
  • Example: Pretty-print a list of lists

The textwrap module is useful to wrap or truncate long strings instead of lists or dictionaries. See the following article.

In the sample code, the pprint module is imported as follows, and the list of dictionaries is used as an example. The pprint module is included in the standard library, so it is unnecessary to install it additionally.

import pprint

l = [{'Name': 'Alice XXX', 'Age': 40, 'Points': [80, 20]}, 
     {'Name': 'Bob YYY', 'Age': 20, 'Points': [90, 10]},
     {'Name': 'Charlie ZZZ', 'Age': 30, 'Points': [70, 30]}]

Basic usage of pprint

The normal print() function prints out the elements of a list or dictionary on a single line without any line breaks.

print(l)
# [{'Name': 'Alice XXX', 'Age': 40, 'Points': [80, 20]}, {'Name': 'Bob YYY', 'Age': 20, 'Points': [90, 10]}, {'Name': 'Charlie ZZZ', 'Age': 30, 'Points': [70, 30]}]

With pprint.pprint(), each element of the list will be broken into a new line as shown below, making it easier to read.

pprint.pprint(l)
# [{'Age': 40, 'Name': 'Alice XXX', 'Points': [80, 20]},
#  {'Age': 20, 'Name': 'Bob YYY', 'Points': [90, 10]},
#  {'Age': 30, 'Name': 'Charlie ZZZ', 'Points': [70, 30]}]

The line break position is determined by the argument settings described below.

Note that, as shown in the example above, the elements of the dictionary are sorted in the order of the keys. If the parameter sort_dicts, added in Python 3.8, is set to False (default: True), the order of the dictionaries is kept, but in earlier versions, they are always sorted.

If you want to convert it to a string str instead of outputting it, use pprint.pformat() described below.

Specify the output width (number of characters): width

The output width (number of characters) can be specified with width.

The line is broken to fit the specified number of characters. The default value is width=80.

pprint.pprint(l, width=40)
# [{'Age': 40,
#   'Name': 'Alice XXX',
#   'Points': [80, 20]},
#  {'Age': 20,
#   'Name': 'Bob YYY',
#   'Points': [90, 10]},
#  {'Age': 30,
#   'Name': 'Charlie ZZZ',
#   'Points': [70, 30]}]

If width is large, no newline is inserted, and the output is the same as print().

pprint.pprint(l, width=200)
# [{'Age': 40, 'Name': 'Alice XXX', 'Points': [80, 20]}, {'Age': 20, 'Name': 'Bob YYY', 'Points': [90, 10]}, {'Age': 30, 'Name': 'Charlie ZZZ', 'Points': [70, 30]}]

A line is broken at an element of a list or a dictionary, not between key and value of a dictionary, nor in the middle of a number. Therefore, it does not always fit into the width of the number of characters specified by width.

Note that strings may be broken into a new line for each word.

pprint.pprint(l, width=1)
# [{'Age': 40,
#   'Name': 'Alice '
#           'XXX',
#   'Points': [80,
#              20]},
#  {'Age': 20,
#   'Name': 'Bob '
#           'YYY',
#   'Points': [90,
#              10]},
#  {'Age': 30,
#   'Name': 'Charlie '
#           'ZZZ',
#   'Points': [70,
#              30]}]

Specify the output depth: depth

The output depth can be specified with depth. The depth here means the depth of nesting.

Elements nested deeper than the specified value are printed with the ellipsis ....

pprint.pprint(l, depth=1)
# [{...}, {...}, {...}]

pprint.pprint(l, depth=2)
# [{'Age': 40, 'Name': 'Alice XXX', 'Points': [...]},
#  {'Age': 20, 'Name': 'Bob YYY', 'Points': [...]},
#  {'Age': 30, 'Name': 'Charlie ZZZ', 'Points': [...]}]

The default value is depth=None, and all elements are output.

You can specify both width and depth at the same time. The depth specifies the depth of the data structure, not the number of lines. The line break positions depend on the number of characters specified by width.

pprint.pprint(l, depth=2, width=40)
# [{'Age': 40,
#   'Name': 'Alice XXX',
#   'Points': [...]},
#  {'Age': 20,
#   'Name': 'Bob YYY',
#   'Points': [...]},
#  {'Age': 30,
#   'Name': 'Charlie ZZZ',
#   'Points': [...]}]

Specify the indent width: indent

The indent width can be specified with indent. The default value is indent=1.

pprint.pprint(l, indent=4, width=4)
# [   {   'Age': 40,
#         'Name': 'Alice '
#                 'XXX',
#         'Points': [   80,
#                       20]},
#     {   'Age': 20,
#         'Name': 'Bob '
#                 'YYY',
#         'Points': [   90,
#                       10]},
#     {   'Age': 30,
#         'Name': 'Charlie '
#                 'ZZZ',
#         'Points': [   70,
#                       30]}]

Reduce line breaks: compact

By default, all elements of a list or dictionary break lines if they do not fit into width.

l_long = [list(range(10)), list(range(100, 110))]

print(l_long)
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [100, 101, 102, 103, 104, 105, 106, 107, 108, 109]]

pprint.pprint(l_long, width=40)
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
#  [100,
#   101,
#   102,
#   103,
#   104,
#   105,
#   106,
#   107,
#   108,
#   109]]

If compact is set to True, elements that fit into width are printed on a single line. It is better to use compact=True for lists with many elements.

pprint.pprint(l_long, width=40, compact=True)
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
#  [100, 101, 102, 103, 104, 105, 106,
#   107, 108, 109]]

Note that compact was added in Python 3.4, so it cannot be used in earlier versions.

Convert to string: pprint.pformat()

Dictionaries and lists can be converted to the string with str(). In this case, they are converted to a one-line string without newline, as in the output of print().

s_normal = str(l)
print(s_normal)
# [{'Name': 'Alice XXX', 'Age': 40, 'Points': [80, 20]}, {'Name': 'Bob YYY', 'Age': 20, 'Points': [90, 10]}, {'Name': 'Charlie ZZZ', 'Age': 30, 'Points': [70, 30]}]

print(type(s_normal))
# <class 'str'>

You can use pprint.pformat() to get the output of pprint.pprint() as the string str.

s_pp = pprint.pformat(l)
print(s_pp)
# [{'Age': 40, 'Name': 'Alice XXX', 'Points': [80, 20]},
#  {'Age': 20, 'Name': 'Bob YYY', 'Points': [90, 10]},
#  {'Age': 30, 'Name': 'Charlie ZZZ', 'Points': [70, 30]}]

print(type(s_pp))
# <class 'str'>

The parameters of pprint.pformat() is the same as pprint.pprint().

s_pp = pprint.pformat(l, depth=2, width=40, indent=2)
print(s_pp)
# [ { 'Age': 40,
#     'Name': 'Alice XXX',
#     'Points': [...]},
#   { 'Age': 20,
#     'Name': 'Bob YYY',
#     'Points': [...]},
#   { 'Age': 30,
#     'Name': 'Charlie ZZZ',
#     'Points': [...]}]

Example: Pretty-print a list of lists

A list of lists is hard to read with print(), so use pprint.pprint().

l_2d = [list(range(10)), list(range(10)), list(range(10))]

print(l_2d)
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

pprint.pprint(l_2d)
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
#  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
#  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

As mentioned above, where to start a new line is determined by the number of characters specified by width.

If the number of elements is small, it fits into the default output width width=80, so there is no line break.

l_2d = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

print(l_2d)
# [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

pprint.pprint(l_2d)
# [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

If an appropriat width is specified, the line will be broken.

pprint.pprint(l_2d, width=20)
# [[0, 1, 2],
#  [3, 4, 5],
#  [6, 7, 8]]

If you want to get it as a string, use pprint.pformat().

 s = pprint.pformat(l_2d, width=20)
print(s)
# [[0, 1, 2],
#  [3, 4, 5],
#  [6, 7, 8]]

print(type(s))
# <class 'str'>

标签:20,Name,Python,Age,pprint,width,Points,print
From: https://www.cnblogs.com/lfri/p/17211873.html

相关文章

  • python-字符串相关方法
    一、访问字符串中的值1、根据下标获取元素#根据下标获取字符word="hello"print(word[2])#输出l2、切片式范围截取#方括号内输入下标范围,截取字符串;word=......
  • 桌面文件又多又乱?教你用Python一键清理,只需20行代码轻松实现!
    我这个人比较懒,总是喜欢把收到的重要文件,或者比较紧急的文件放到桌面,久而久之,桌面或者文件夹越来越乱。不知道大家是不是像我一样的我滴妈呀,看着就很崩溃!之......
  • 2.datax条件python3.6安装
    一.安装python3.6.11.安装依赖环境(必须安装否则会出现python3编译器中不能使用退格键和方向键)yuminstallreadline-develgccmakepatchgdbm-developenssl-develsql......
  • python 程序 jenkins 打包的过程
     jenkins打包的过程1、如果有依赖文件,必须命名成requirements.txt放到site-packages文件夹下面,这样 jenkins才会把下载 requirements.txt里面的包,再打包成app......
  • 使用Python训练好的决策树模型生成C++代码
    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档文章目录前言一、决策树模型二、解析决策树模型1.模型分解2.构建决策二叉树3.生成代码3.1生成python代......
  • AI机器学习模型python到C/C++的转换播
    了解过机器学习的人应该都知道python的sklearn库非常好用的机器学习助手。从sklearn导入某个机器学习的库,调用fit函数即可生成模型,用来预测测试数据。1、保存模型如......
  • Python数据分析之航空公司客户价值分析
    #代码7-2#对数据的分布分析importpandasaspdimportmatplotlib.pyplotaspltdatafile='C:/Users/justaplayer/Documents/WeChatFiles/wxid_dcbvylvcfew......
  • python爬取彼岸桌面4K壁纸
    importrequestsfromlxmlimportetreeimportosurl='https://pic.netbian.com/4kmeinv/index.html'headers={'user-agent':'Mozilla/5.0(WindowsNT10......
  • python爬虫案列03,爬取58二手房信息
    importrequestsfromlxmlimportetreeurl="https://fy.58.com/ershoufang/?PGTID=0d100000-0091-53ca-4993-576198ca62e3"headers={"user-agent":"Mozilla/5.......
  • Python常见面试题013.请说出下面的代码返回结果是什么?
    013.请说出下面的代码返回结果是什么?*的坑;简单题参考:https://docs.python.org/zh-cn/3.9/library/stdtypes.html#typesseq示例代码lists=[[]]*3lists[0].appen......