您好,欢迎访问一九零五行业门户网

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 pprintprint 'print:'print dataprint 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 loggingfrom pprint import pformatlogging.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 datadebug [(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, ]['a', 'b', 1, 2, [...]]
在这个例子中,列表local_data增加到了其自身,这会创建一个递归引用
内置函数id()作用是获得对象的id值,理论上讲每个对象都有一个id值,如果是整数和字符串((相对较小的时候)),那么相同的值会有相同的id值,但是如果是类,及时相同也会有不同的id值。测试如下:
#int or float or lon 都一样(比较小的时候)a = 65464131311513lb = 65464131311513lc = 65464131311513lprint id(a)print id(b)print id(c)printa = '12312312'b = '12312312'c = '12312312'print id(a)print id(b)print id(c)print a = 65464131311513l*11b = 65464131311513l*11c = 65464131311513l*11print id(a)print id(b)print id(c)printa = '12312312'*11b = '12312312'*11c = '12312312'*11print id(a)print id(b)print id(c)print class test(object): def __init__(self): passa = test()b = test()c = test()print id(a)print id(b)print id(c)print
测试结果:
470103421749924701034217499247010342174992470103432720964701034327209647010343272096470103432615684701034326164847010343261688470103432009444701034319915247010343202352470103432523044701034325294447010343253008
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 pprintfor 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'})]
宽度大小不能适应格式化数据结构时,如果斩断或转行会引入非法的语法,就不会进行截断或转行。
其它类似信息

推荐信息