Python 简明教程

Python - Output Formatting

Output Formatting in Python

Python 中的输出格式化用于使代码更具可读性,使输出更具用户友好性。无论你显示的是简单的文本字符串、复杂的数据结构还是创建报告,Python 都提供了多种方法来格式化输出。

这些方法包括使用:

  1. 字符串模运算符 (%)

  2. The format() method

  3. f 字符串(格式化字符串文本)

  4. The template strings

此外,Python 的 “textwrap” 和 “pprint” 模块提供了用于换行和漂亮地打印数据结构的高级功能。

Using String Modulo Operator (%)

我们可以使用字符串模运算符 % 来格式化输出。此运算符仅适用于字符串,且可用作 C 的 printf() 族中函数的集合。与 C 中的那些占位符类似,格式规范符号如 %d%c%f%s 用作字符串中的占位符。

以下是一个简单的示例:

print ("My name is %s and weight is %d kg!" % ('Zara', 21))

它将生成以下 output

My name is Zara and weight is 21 kg!

Using the format() Method

我们可以使用 format() 方法来格式化输出,该方法在 Python 3.0 中引入,并已移植至 Python 2.6 和 2.7。

format() 方法是内置 string 类的组成部分,且允许多变量替换和值格式化。与字符串模运算符相比,它被认为是格式化字符串的一种更加优雅灵活的方法。

Syntax

format() 方法的一般语法如下:

str.format(var1, var2,...)

Return Value

该方法返回一个格式化字符串。

该字符串本身包含占位符 {},其中依次插入变量的值。

Example

name="Rajesh"
age=23
print ("my name is {} and my age is {} years".format(name, age))

它将生成以下 output

my name is Rajesh and my age is 23 years

可以将变量用作 format() 方法的关键字参数,并将变量名用作字符串中的占位符。

print ("my name is {name} and my age is {age}
years".format(name="Rajesh", age=23))

Using F-Strings

f 字符串,即格式化字符串文本,是一种在 Python 中格式化字符串的方法,这种方法简单、快速且易于阅读。你可以通过在字符串的开引号前添加 f 来创建 f 字符串。

可以在字符串中包含变量的占位符,这些占位符用花括号 {} 括起来。这些变量的值将插入字符串的那些位置。

Example

在此示例中,变量 “name” 和 “age” 插入字符串中,它们各自的占位符 “{name}” 和 “{age}” 所在的位置。f 字符串可以轻松地在字符串中包含变量值,而无需使用 format() 方法或字符串连接:

name = 'Rajesh'
age = 23

fstring = f'My name is {name} and I am {age} years old'
print (fstring)

它将生成以下 output

My name is Rajesh and I am 23 years old

Format Conversion Rule in Python

你还可以指定 C 风格的格式化符号。唯一改变是使用 : 替换 % 。例如,使用 {:s} 替换 %s ,使用 {:d} 替换 %d ,如下所示:

name = "Rajesh"
age = 23
print("my name is {:s} and my age is {:d} years".format(name, age))

输出如下:

my name is Rajesh and my age is 23 years

Template Strings

string 模块中的 Template 类提供了格式化字符串的另一种方法,该方法支持动态格式化。Template 类的其中一个优点是可以定制格式化规则。

有效的模板字符串或占位符由两部分组成:“ $ ”符号后跟有效的 Python 标识符。

您需要创建 Template 类的对象,并将模板字符串用作构造函数的参数。接下来,调用 Template 类的“ substitute() ”方法。它将作为参数提供的值放在模板字符串的位置。

Example

from string import Template

temp_str = "My name is $name and I am $age years old"
tempobj = Template(temp_str)
ret = tempobj.substitute(name='Rajesh', age=23)
print (ret)

它将生成以下 output

My name is Rajesh and I am 23 years old

The textwrap Module

Python 的 textwrap 模块中的 wrap 类包含通过调整输入段落中的换行来设置和包装纯文本的功能。它有助于使文本格式正确且美观。

textwrap 模块具有以下便捷功能:

textwrap.wrap(text, width=70)

textwrap.wrap() 函数将单段落文字(字符串)换行,这样每一行长度最多为 width 个字符。返回输出行列表,不包括最后的新行。可选关键字参数对应于 TextWrapper 的实例属性。width 的默认值为 70。

textwrap.fill(text, width=70)

textwrap.fill() 函数将单段落文字换行,并返回包含换行段落的单个字符串。

这两种方法都在内部创建 TextWrapper 类的对象并对其调用单个方法。由于实例未被重用,因此你创建自己的 TextWrapper 对象将更有效率。

Example

import textwrap

text = '''
Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation via the off-side rule.

Python is dynamically typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly procedural), object-oriented and functional programming. It is often described as a "batteries included" language due to its comprehensive standard library.
'''

wrapper = textwrap.TextWrapper(width=40)
wrapped = wrapper.wrap(text = text)

# Print output
for element in wrapped:
   print(element)

它将生成以下 output

Python is a high-level, general-purpose
programming language. Its design
philosophy emphasizes code readability
with the use of significant indentation
via the off-side rule. Python is
dynamically typed and garbage-collected.
It supports multiple programming
paradigms, including structured
(particularly procedural), objectoriented and functional programming. It
is often described as a "batteries
included" language due to its
comprehensive standard library.

下列属性针对 TextWrapper 对象进行定义 −

  1. width − (默认: 70) 已包装行的最大长度。

  2. expand_tabs − (默认: True) 如果为 true,则文本中的所有制表符都将使用文本的 expandtabs() 方法展开为空格。

  3. tabsize − (默认: 8) 如果 expand_tabs 为 true,则文本中的所有制表符都将根据当前列和给定的制表符大小展开为零个或多个空格。

  4. replace_whitespace − (默认: True) 如果为 true,则在制表符展开后但在包装前,wrap() 方法将用一个空格替换每个空白字符。

  5. drop_whitespace − (默认: True) 如果为 true,则每行开始和结束处的空白字符(包装后但在缩进前)都会被去掉。然而,如果段落开始处后的字符不是空白,则段落开始处的空白字符不会被去掉。如果被去掉的空白字符占据了整行,则整行将被去掉。

  6. initial_indent − (默认: '') 将被添加至已包装输出的第一行的开头处的字符串。

  7. subsequent_indent − (默认: '') 将被添加至已包装输出的所有行(第一行除外)的开头处的字符串。

  8. fix_sentence_endings − (默认: False) 如果为 true,则 TextWrapper 尝试检测句子结尾并确保句子始终用正好两个空格分隔。对于使用等宽字体显示的文本,此属性通常是必需的。

  9. break_long_words − (默认: True) 如果为 true,则长于 width 的单词将被折行以确保任何行都不长于 width。如果为 false,则不会折行长单词,而且一些行可能长于 width。

  10. break_on_hyphens − (默认: True) 如果为 true,则包装将优选在复合词中的空格和连字符后进行,这符合英语的习惯。如果为 false,则仅空格将被视为潜在的良好的换行位置。

The shorten() Function

shorten() 函数折叠和截断给定文本以使其适合给定的宽度。文本首先会折叠其空格。如果它适合“ width ”,则按原样返回。否则,尽可能多地连接单词,然后附加占位符 −

Example

import textwrap

python_desc = """Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language."""

my_wrap = textwrap.TextWrapper(width = 40)

short_text = textwrap.shorten(text = python_desc, width=150)
print('\n\n' + my_wrap.fill(text = short_text))

它将生成以下 output

Python is a general-purpose interpreted,
interactive, object-oriented,and high
level programming language. It was
created by Guido van Rossum [...]

The pprint Module

Python 标准库中的“ pprint ”模块可以很好地显示 Python 数据结构。pprint 的名称代表漂亮打印机。Python 解释器可以正确解析的任何数据结构都将以优雅的方式进行格式化。

已格式化的表达式将尽可能地保存在一行中,但如果长度超出了格式化的 width 参数,则会拆分为多行。pprint 输出的一个独特功能是,在格式化显示表示形式之前,会自动对字典进行排序。

PrettyPrinter Class

pprint 模块包含“ PrettyPrinter ”类的定义。它的构造函数采用以下格式 −

Syntax

pprint.PrettyPrinter(indent, width, depth, stream, compact)

Parameters

  1. indent − 为每个递归级别添加的缩进。默认值为 1。

  2. width − 默认值为 80。所需的输出受到此值限制。如果长度大于 width,则会拆分为多行。

  3. depth − 控制要打印级别的数量。

  4. stream − 默认为 std.out − 默认输出设备。它可以采用任何流对象,如文件。

  5. compact − id 默认为 False。如果为 true,则只显示可在宽度内调整的数据。

PrettyPrinter 类定义了以下方法−

pprint() method

pprint() 方法打印 PrettyPrinter 对象的格式化表示。

pformat() method

pformat() 方法返回对象格式化的表示,该表示基于构造函数的参数。

Example

以下示例演示了 PrettyPrinter 类的一个简单用法 −

import pprint
students={"Dilip":["English", "Maths", "Science"],"Raju":{"English":50,"Maths":60, "Science":70},"Kalpana":(50,60,70)}
pp=pprint.PrettyPrinter()
print ("normal print output")
print (students)
print ("----")
print ("pprint output")
pp.pprint(students)

输出显示了正常打印和美观打印显示 −

normal print output
{'Dilip': ['English', 'Maths', 'Science'], 'Raju': {'English': 50, 'Maths': 60, 'Science': 70}, 'Kalpana': (50, 60, 70)}

pprint 输出{'Dilip': ['英语', '数学', '科学'], 'Kalpana': (50, 60, 70), 'Raju': {'英语': 50, '数学': 60, '科学': 70}}

The *pprint* module also defines convenience functions pprint() and pformat() corresponding to PrettyPrinter methods. The example below uses pprint() function.

[source, python]

from pprint import pprintstudents={"Dilip":["英语", "数学", "科学"], "Raju":{"英语":50,"数学":60, "科学":70}, "Kalpana":(50,60,70)}print ("普通打印输出")print (students)print ("----")print ("pprint 输出")pprint (students)

==== Example Using pformat() Method

The next example uses pformat() method as well as pformat() function. To use pformat() method, PrettyPrinter object is first set up. In both cases, the formatted representation is displayed using normal print() function.

[source, python]

import pprintstudents={"Dilip":["英语", "数学", "科学"], "Raju":{"英语":50,"数学":60, "科学":70}, "Kalpana":(50,60,70)}print ("使用 pformat 方法")pp=pprint.PrettyPrinter()string=pp.pformat(students)print (string)print ('------')print ("使用 pformat 函数")string=pprint.pformat(students)print (string)

Here is the output of the above code −

[source, python]

使用 pformat 方法{'Dilip': ['英语', '数学', '科学'], 'Kalpana': (50, 60, 70), 'Raju': {'英语': 50, '数学': 60, '科学': 70}}

using pformat function
{'Dilip': ['English', 'Maths', 'Science'],
 'Kalpana': (50, 60, 70),
 'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}

Pretty printer can also be used with custom classes. Inside the class repr() method is overridden. The repr() method is called when repr() function is used. It is the official string representation of Python object. When we use object as parameter to print() function it prints return value of repr() function.

Example

In this example, the repr() method returns the string representation of player object −

import pprint
class player:
   def __init__(self, name, formats=[], runs=[]):
      self.name=name
      self.formats=formats
      self.runs=runs
   def __repr__(self):
      dct={}
      dct[self.name]=dict(zip(self.formats,self.runs))
      return (repr(dct))

l1=['Tests','ODI','T20']
l2=[[140, 45, 39],[15,122,36,67, 100, 49],[78,44, 12, 0, 23, 75]]
p1=player("virat",l1,l2)
pp=pprint.PrettyPrinter()
pp.pprint(p1)

The output of above code is −

{'virat': {'Tests': [140, 45, 39], 'ODI': [15, 122, 36, 67, 100, 49],
'T20': [78, 44, 12, 0, 23, 75]}}