Python中使用pprint函数进行格式化输出的教程
pprint – 美观打印
作用:美观打印数据结构
pprint 包含一个“美观打印机”,用于生成数据结构的一个美观视图。格式化工具会生成数据结构的一些表示,不仅可以由解释器正确地解析,而且便于人类阅读。输出尽可能放在一行上,分解为多行时则需要缩进。
以下实例用用到的data包含一下数据
data = [(1,{'a':'A','b':'B','c':'C','d':'D'}), (2,{'e':'E','f':'F','g':'G','h':'H', 'i':'I','j':'J','k':'K','l':'L' }), ]
1、 打印
要使用这个模块,最简单的方法就是利用pprint()函数
from pprint import pprint print 'PRINT:' print data print print 'PPRINT:' pprint(data)
运行结果:
PRINT: [(1, {'a': 'A', 'c': 'C', 'b': 'B', 'd': 'D'}), (2, {'e': 'E', 'g': 'G', 'f': 'F', 'i': 'I', 'h': 'H', 'k': 'K', 'j': 'J', 'l': 'L'})] PPRINT: [(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}), (2, {'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H', 'i': 'I', 'j': 'J', 'k': 'K', 'l': 'L'})]
pprint()格式化一个对象,并把它写至一个数据流,这个数据流作为参数传入(或者是默认的sys.stdout)
注意为什么第二个字典中会显示一竖列,因为pprint打印支持8个对象以上的竖列打印
2、 格式化
格式化一个数据结构而不把它直接写至一个流(例如用于日志记录),可以使用pformat()来构造一个字符串表示。
import logging from pprint import pformat logging.basicConfig(level = logging.DEBUG, format = '%(levelname)-8s %(message)s', ) logging.debug('Logging pformatted data') formatted = pformat(data) for line in formatted.splitlines(): logging.debug(line.rstrip())
运行结果:
DEBUG Logging pformatted data DEBUG [(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}), DEBUG (2, DEBUG {'e': 'E', DEBUG 'f': 'F', DEBUG 'g': 'G', DEBUG 'h': 'H', DEBUG 'i': 'I', DEBUG 'j': 'J', DEBUG 'k': 'K', DEBUG 'l': 'L'})]
然后可以单独低打印格式化的字符串或者计入日志
splitlines() 按行分割()
rstrip()去除右边的空格 lstrip()去除左边的空格 strip()去除两边空格。默认为去除空格,也可以传入需要从两边或者其中一边去除的字符,如strip(‘a')就是去除字符串两边的字符'a'
3、 任意类
如果定制类定义了一个__repr__()方法,pprint()使用的PrettyPrinter类还可以处理这些定制类。
from pprint import pprint class node(object): def __init__(self,name,contents =[]): self.name = name self.contents = contents[:] def __repr__(self): return ('node(' + repr(self.name) + ',' + repr(self.contents) + ')' ) trees = [node('node-1'), node('node-2',[node('node-2-1')]), node('node-3',[node('node-3-1')]), ] pprint(trees)
运行结果:
[node('node-1',[]), node('node-2',[node('node-2-1',[])]), node('node-3',[node('node-3-1',[])])]
由PrettyPrinter组合嵌套对象的表示,从而返回完整字符串表示。
4、 递归
递归数据结构有指向原数据源的引用来表示,形式为
from pprint import pprint local_data = ['a','b',1,2] local_data.append(local_data) print 'id(local_data) =>',id(local_data) pprint(local_data) print local_data
运行结果:
id(local_data) => 47458332363520 ['a', 'b', 1, 2, <Recursion on list with id=47458332363520>] ['a', 'b', 1, 2, [...]]
在这个例子中,列表local_data增加到了其自身,这会创建一个递归引用
内置函数id()作用是获得对象的id值,理论上讲每个对象都有一个id值,如果是整数和字符串((相对较小的时候)),那么相同的值会有相同的id值,但是如果是类,及时相同也会有不同的id值。测试如下:
#int or float or lon 都一样(比较小的时候) a = 65464131311513l b = 65464131311513l c = 65464131311513l print id(a) print id(b) print id(c) print a = '12312312' b = '12312312' c = '12312312' print id(a) print id(b) print id(c) print a = 65464131311513l*11 b = 65464131311513l*11 c = 65464131311513l*11 print id(a) print id(b) print id(c) print a = '12312312'*11 b = '12312312'*11 c = '12312312'*11 print id(a) print id(b) print id(c) print class Test(object): def __init__(self): pass a = Test() b = Test() c = Test() print id(a) print id(b) print id(c) print
测试结果:
47010342174992 47010342174992 47010342174992 47010343272096 47010343272096 47010343272096 47010343261568 47010343261648 47010343261688 47010343200944 47010343199152 47010343202352 47010343252304 47010343252944 47010343253008
5、 限制嵌套输出
对于非常深的数据结构,可能不要求输出包含所有细节。有可能数据没有是当地格式化,也可能格式化文本过大而无法管理,或者默写数据时多余的。
from pprint import pprint print 'depth 1 :' pprint(data,depth=1) print print 'depth 2 :' pprint(data,depth=2) print print 'depth 3 :' pprint(data,depth=3)
运行结果:
depth 1 : [(...), (...)] depth 2 : [(1, {...}), (2, {...})] depth 3 : [(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}), (2, {'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H', 'i': 'I', 'j': 'J', 'k': 'K', 'l': 'L'})]
使用depth参数可以控制美观打印机递归处理嵌套数据结构的深度。输出中未包含的层次由一个省略号表示
6、 控制输出宽度
格式化文本的默认输出宽度为80列。要调整这个宽度,可以再pprint()中使用参数width。
from pprint import pprint for width in [80,5]: print 'WIDTH = ', width pprint(data,width = width) print
运行结果:
WIDTH = 80 [(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}), (2, {'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H', 'i': 'I', 'j': 'J', 'k': 'K', 'l': 'L'})] WIDTH = 5 [(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}), (2, {'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H', 'i': 'I', 'j': 'J', 'k': 'K', 'l': 'L'})]
宽度大小不能适应格式化数据结构时,如果斩断或转行会引入非法的语法,就不会进行截断或转行。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.
