Python 简明教程
Python - Output Formatting
Output Formatting in Python
Python 中的输出格式化用于使代码更具可读性,使输出更具用户友好性。无论你显示的是简单的文本字符串、复杂的数据结构还是创建报告,Python 都提供了多种方法来格式化输出。
Output formatting in Python is used to make your code more readable and your output more user-friendly. Whether you are displaying simple text strings, complex data structures, or creating reports, Python offers several ways for formatting output.
这些方法包括使用:
These ways include using −
-
The string modulo operator (%)
-
The format() method
-
The f-strings (formatted string literals)
-
The template strings
此外,Python 的 “textwrap” 和 “pprint” 模块提供了用于换行和漂亮地打印数据结构的高级功能。
Additionally, Python’s "textwrap" and "pprint" modules offer advanced functionalities for wrapping text and pretty-printing data structures.
Using String Modulo Operator (%)
我们可以使用字符串模运算符 % 来格式化输出。此运算符仅适用于字符串,且可用作 C 的 printf() 族中函数的集合。与 C 中的那些占位符类似,格式规范符号如 %d 、 %c 、 %f 和 %s 用作字符串中的占位符。
We can format output using the string modulo operator %. This operator is unique to strings and makes up for the pack of having functions from C’s printf() family. Format specification symbols like %d, %c, %f, and %s are used as placeholders in a string, similar to those in C.
以下是一个简单的示例:
Following is a simple example −
print ("My name is %s and weight is %d kg!" % ('Zara', 21))
它将生成以下 output −
It will produce the following output −
My name is Zara and weight is 21 kg!
Using the format() Method
我们可以使用 format() 方法来格式化输出,该方法在 Python 3.0 中引入,并已移植至 Python 2.6 和 2.7。
We can format output using the format() method, which was introduced in Python 3.0 and has been backported to Python 2.6 and 2.7.
format() 方法是内置 string 类的组成部分,且允许多变量替换和值格式化。与字符串模运算符相比,它被认为是格式化字符串的一种更加优雅灵活的方法。
The format() method is part of the built-in string class and allows for complex variable substitutions and value formatting. It is considered a more elegant and flexible way to format strings compared to the string modulo operator.
Syntax
format() 方法的一般语法如下:
The general syntax of format() method is as follows −
str.format(var1, var2,...)
Return Value
该方法返回一个格式化字符串。
The method returns a formatted string.
该字符串本身包含占位符 {},其中依次插入变量的值。
The string itself contains placeholders {} in which values of variables are successively inserted.
Example
name="Rajesh"
age=23
print ("my name is {} and my age is {} years".format(name, age))
它将生成以下 output −
It will produce the following output −
my name is Rajesh and my age is 23 years
可以将变量用作 format() 方法的关键字参数,并将变量名用作字符串中的占位符。
You can use variables as keyword arguments to format() method and use the variable name as the placeholder in the string.
print ("my name is {name} and my age is {age}
years".format(name="Rajesh", age=23))
Using F-Strings
f 字符串,即格式化字符串文本,是一种在 Python 中格式化字符串的方法,这种方法简单、快速且易于阅读。你可以通过在字符串的开引号前添加 f 来创建 f 字符串。
F-strings, or formatted string literals, are a way to format strings in Python that is simple, fast, and easy to read. You create an f-string by adding an f before the opening quotation mark of a string.
可以在字符串中包含变量的占位符,这些占位符用花括号 {} 括起来。这些变量的值将插入字符串的那些位置。
Inside the string, you can include placeholders for variables, which are enclosed in curly braces {}. The values of these variables will be inserted into the string at those places.
Example
在此示例中,变量 “name” 和 “age” 插入字符串中,它们各自的占位符 “{name}” 和 “{age}” 所在的位置。f 字符串可以轻松地在字符串中包含变量值,而无需使用 format() 方法或字符串连接:
In this example, the variables "name" and "age" are inserted into the string where their placeholders "{name}" and "{age}" are located. F-strings make it easy to include variable values in strings without having to use the format() method or string concatenation −
name = 'Rajesh'
age = 23
fstring = f'My name is {name} and I am {age} years old'
print (fstring)
它将生成以下 output −
It will produce the following output −
My name is Rajesh and I am 23 years old
Format Conversion Rule in Python
你还可以指定 C 风格的格式化符号。唯一改变是使用 : 替换 % 。例如,使用 {:s} 替换 %s ,使用 {:d} 替换 %d ,如下所示:
You can also specify C-style formatting symbols. The only change is using : instead of %. For example, instead of %s use {:s} and instead of %d use {:d} as shown below −
name = "Rajesh"
age = 23
print("my name is {:s} and my age is {:d} years".format(name, age))
输出如下:
You will get the output as shown below −
my name is Rajesh and my age is 23 years
Template Strings
string 模块中的 Template 类提供了格式化字符串的另一种方法,该方法支持动态格式化。Template 类的其中一个优点是可以定制格式化规则。
The Template class in string module provides an alternative method to format the strings dynamically. One of the benefits of Template class is to be able to customize the formatting rules.
有效的模板字符串或占位符由两部分组成:“ $ ”符号后跟有效的 Python 标识符。
A valid template string, or placeholder, consists of two parts: The $ symbol followed by a valid Python identifier.
您需要创建 Template 类的对象,并将模板字符串用作构造函数的参数。接下来,调用 Template 类的“ substitute() ”方法。它将作为参数提供的值放在模板字符串的位置。
You need to create an object of Template class and use the template string as an argument to the constructor. Next, call the substitute() method of Template class. It puts the values provided as the parameters in place of template strings.
The textwrap Module
Python 的 textwrap 模块中的 wrap 类包含通过调整输入段落中的换行来设置和包装纯文本的功能。它有助于使文本格式正确且美观。
The wrap class in Python’s textwrap module contains functionality to format and wrap plain texts by adjusting the line breaks in the input paragraph. It helps in making the text wellformatted and beautiful.
textwrap 模块具有以下便捷功能:
The textwrap module has the following convenience functions −
textwrap.wrap(text, width=70)
textwrap.wrap() 函数将单段落文字(字符串)换行,这样每一行长度最多为 width 个字符。返回输出行列表,不包括最后的新行。可选关键字参数对应于 TextWrapper 的实例属性。width 的默认值为 70。
The textwrap.wrap() function wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines. Optional keyword arguments correspond to the instance attributes of TextWrapper. width defaults to 70.
textwrap.fill(text, width=70)
textwrap.fill() 函数将单段落文字换行,并返回包含换行段落的单个字符串。
The textwrap.fill() function wraps the single paragraph in text, and returns a single string containing the wrapped paragraph.
这两种方法都在内部创建 TextWrapper 类的对象并对其调用单个方法。由于实例未被重用,因此你创建自己的 TextWrapper 对象将更有效率。
Both methods internally create an object of TextWrapper class and calling a single method on it. Since the instance is not reused, it will be more efficient for you to create your own TextWrapper object.
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 −
It will produce the following 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 对象进行定义 −
Following attributes are defined for a TextWrapper object −
-
width − (default: 70) The maximum length of wrapped lines.
-
expand_tabs − (default: True) If true, then all tab characters in text will be expanded to spaces using the expandtabs() method of text.
-
tabsize − (default: 8) If expand_tabs is true, then all tab characters in text will be expanded to zero or more spaces, depending on the current column and the given tab size.
-
replace_whitespace − (default: True) If true, after tab expansion but before wrapping, the wrap() method will replace each whitespace character with a single space.
-
drop_whitespace − (default: True) If true, whitespace at the beginning and ending of every line (after wrapping but before indenting) is dropped. Whitespace at the beginning of the paragraph, however, is not dropped if non-whitespace follows it. If whitespace being dropped takes up an entire line, the whole line is dropped.
-
initial_indent − (default: '') String that will be prepended to the first line of wrapped output.
-
subsequent_indent − (default: '') String that will be prepended to all lines of wrapped output except the first.
-
fix_sentence_endings − (default: False) If true, TextWrapper attempts to detect sentence endings and ensure that sentences are always separated by exactly two spaces. This is generally desired for text in a monospaced font.
-
break_long_words − (default: True) If true, then words longer than width will be broken in order to ensure that no lines are longer than width. If it is false, long words will not be broken, and some lines may be longer than width.
-
break_on_hyphens − (default: True) If true, wrapping will occur preferably on whitespaces and right after hyphens in compound words, as it is customary in English. If false, only whitespaces will be considered as potentially good places for line breaks.
The shorten() Function
shorten() 函数折叠和截断给定文本以使其适合给定的宽度。文本首先会折叠其空格。如果它适合“ width ”,则按原样返回。否则,尽可能多地连接单词,然后附加占位符 −
The shorten() function collapse and truncate the given text to fit in the given width. The text first has its whitespace collapsed. If it then fits in the width, it is returned as is. Otherwise, as many words as possible are joined and then the placeholder is appended −
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 −
It will produce the following 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 解释器可以正确解析的任何数据结构都将以优雅的方式进行格式化。
The pprint module in Python’s standard library enables aesthetically good looking appearance of Python data structures. The name pprint stands for pretty printer. Any data structure that can be correctly parsed by Python interpreter is elegantly formatted.
已格式化的表达式将尽可能地保存在一行中,但如果长度超出了格式化的 width 参数,则会拆分为多行。pprint 输出的一个独特功能是,在格式化显示表示形式之前,会自动对字典进行排序。
The formatted expression is kept in one line as far as possible, but breaks into multiple lines if the length exceeds the width parameter of formatting. One unique feature of pprint output is that the dictionaries are automatically sorted before the display representation is formatted.
PrettyPrinter Class
pprint 模块包含“ PrettyPrinter ”类的定义。它的构造函数采用以下格式 −
The pprint module contains definition of PrettyPrinter class. Its constructor takes following format −
Parameters
-
indent − defines indentation added on each recursive level. Default is 1.
-
width − by default is 80. Desired output is restricted by this value. If the length is greater than width, it is broken in multiple lines.
-
depth − controls number of levels to be printed.
-
stream − is by default std.out − the default output device. It can take any stream object such as file.
-
compact − id set to False by default. If true, only the data adjustable within width will be displayed.
PrettyPrinter 类定义了以下方法−
The PrettyPrinter class defines following methods −
pprint() method
pprint() 方法打印 PrettyPrinter 对象的格式化表示。
The pprint() method prints the formatted representation of PrettyPrinter object.
pformat() method
pformat() 方法返回对象格式化的表示,该表示基于构造函数的参数。
The pformat() method returns the formatted representation of object, based on parameters to the constructor.
Example
以下示例演示了 PrettyPrinter 类的一个简单用法 −
The following example demonstrates a simple use of PrettyPrinter class −
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)
输出显示了正常打印和美观打印显示 −
The output shows normal as well as pretty print display −
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}}
pprint output {'Dilip': ['English', 'Maths', 'Science'], 'Kalpana': (50, 60, 70), 'Raju': {'English': 50, 'Maths': 60, 'Science': 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)
from pprint import pprint students={"Dilip":["English", "Maths", "Science"], "Raju":{"English":50,"Maths":60, "Science":70}, "Kalpana":(50,60,70)} print ("normal print output") print (students) print ("----") print ("pprint output") 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)
import pprint students={"Dilip":["English", "Maths", "Science"], "Raju":{"English":50,"Maths":60, "Science":70}, "Kalpana":(50,60,70)} print ("using pformat method") pp=pprint.PrettyPrinter() string=pp.pformat(students) print (string) print ('------') print ("using pformat function") 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 method {'Dilip': ['English', 'Maths', 'Science'], 'Kalpana': (50, 60, 70), 'Raju': {'English': 50, 'Maths': 60, 'Science': 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]}}