search
HomeBackend DevelopmentPython TutorialPython中使用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'})]

宽度大小不能适应格式化数据结构时,如果斩断或转行会引入非法的语法,就不会进行截断或转行。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools