主页
  • 主页
  • 分类
  • 热文
  • 教程
  • 面试
  • 标签
Python

Python 基础

Python 主页
Python 概述
Python 历史
Python 功能
Python 与 C++
Python Hello World
Python 应用领域
Python 解释器及其模式
Python 环境设置
Python 虚拟环境
Python 语法
Python 变量
Python 数据类型
Python 类型转换
Python Unicode 系统
Python 文字
Python 运算符
Python 算术运算符
Python 比较运算符
Python 赋值运算符
Python 逻辑运算符
Python 位运算符
Python 成员运算符
Python 身份运算符
Python 运算符优先级
Python 注释
Python 用户输入
Python 数字
Python 布尔值

Python 控制语句

Python 控制流
Python 决策
Python if 语句
Python if-else 语句
Python 嵌套 if 语句
Python match-case 语句
Python 循环
Python For 循环
Python for-else 循环
Python while 循环
Python break 语句
Python Continue 语句
Python pass 语句
Python 嵌套循环

Python 函数和模块

Python 函数
Python 默认参数
Python 关键字参数
Python 关键字专用参数
Python 位置参数
Python 仅限位置参数
Python 任意或可变长度参数
Python 变量作用域
Python 函数注释
Python 模块
Python 内置函数

Python 字符串

Python 字符串
Python 字符串切片
Python 字符串修改
Python 字符串连接
Python 字符串格式化
Python 转义字符
Python 字符串方法
Python 字符串练习

Python 列表

Python 列表
Python 访问列表项
Python 更改列表项
Python 添加列表项
Python 删除列表项
Python 循环列表
Python 列表推导式
Python 排序列表
Python 复制列表
Python 合并列表
Python 列表方法
Python 列表练习

Python 元组

Python 元组
Python 访问元组项
Python 更新元组
Python 解包元组项
Python 循环元组
Python 合并元组
Python 元组方法
Python 元组练习

Python 集合

Python 集合
Python 访问集合项
Python 添加集合项
Python 删除集合项
Python 循环集合
Python 合并集合
Python 复制集合
Python 集合运算符
Python 集合方法
Python 集合练习

Python 字典

Python 字典
Python 访问字典项
Python 更改字典项
Python 添加字典项
Python 移除字典项
Python 字典视图对象
Python 循环字典
Python 复制字典
Python 嵌套字典
Python 字典方法
Python 字典练习

Python 数组

Python 数组
Python 访问数组项
Python 添加数组项
Python 移除数组项
Python 循环数组
Python 复制数组
Python 反转数组
Python 排序数组
Python 合并数组
Python 数组方法
Python 数组练习

Python 文件处理

Python 文件处理
Python 文件写入
Python 文件读取
Python 重命名和删除文件
Python 目录
Python 文件方法
Python 文件/目录方法
Python OS.Path 方法

Python 面向对象编程

Python OOP 概念
Python 类和对象
Python 类属性
Python 类方法
Python 静态方法
Python 构造函数
Python 访问修饰符
Python 继承
Python 多态
Python 方法重写
Python 方法重载
Python 动态绑定
Python 动态类型
Python 抽象
Python 封装
Python 接口
Python 包
Python 内部类
Python 匿名类和对象
Python 单例类
Python 包装器类
Python 枚举
Python 反射

Python 错误和异常

Python 语法错误
Python 异常处理
Python Try-Except
Python Try-Finally
Python 抛出异常
Python 异常链
Python 嵌套 try
Python 用户定义异常
Python 日志记录
Python 断言
Python 内置异常

Python 多线程

Python 多线程
Python 线程生命周期
Python 创建线程
Python 启动线程
Python 合并线程
Python 命名线程
Python 线程调度
Python 线程池
Python 主线程
Python 线程优先级
Python 守护线程
Python 线程同步

Python 同步

Python 线程间通信
Python 死锁
Python 中断线程

Python 网络

Python 网络编程
Python 套接字编程
Python URL 处理
Python 泛型

Python 杂项

Python Date and Time
Python math模块
Python 迭代器
Python 生成器
Python 闭包
Python 装饰器
Python 递归
Python 正则表达式
Python Pip
Python 数据库访问
Python 弱引用
Python 序列化
Python 模板技术
Python 输出格式化
Python 性能测量
Python 数据压缩
Python 通用网关接口
Python XML 处理
Python 用户界面(GUI)
Python 命令行参数
Python Docstrings
Python JSON
Python 发送电子邮件
Python 进一步扩展
Python 工具/实用程序
Python GUI

Python 高级概念

Python 抽象基类
Python 自定义异常
Python 高阶函数
Python 对象的内部机制
Python 内存管理
Python 元类
Python 元编程
Python 模拟与桩
Python 猴子补丁
Python 信号处理
Python 类型提示
Python 进行自动化
Python Humanize包
Python 上下文管理器
Python 协程
Python 描述符
Python 内存泄漏
Python 不可变数据结构

基础

Python 主页
Python 概述
Python 历史
Python 功能
Python 与 C++
Python Hello World
Python 应用领域
Python 解释器及其模式
Python 环境设置
Python 虚拟环境
Python 语法
Python 变量
Python 数据类型
Python 类型转换
Python Unicode 系统
Python 文字
Python 运算符
Python 算术运算符
Python 比较运算符
Python 赋值运算符
Python 逻辑运算符
Python 位运算符
Python 成员运算符
Python 身份运算符
Python 运算符优先级
Python 注释
Python 用户输入
Python 数字
Python 布尔值

控制语句

Python 控制流
Python 决策
Python if 语句
Python if-else 语句
Python 嵌套 if 语句
Python match-case 语句
Python 循环
Python For 循环
Python for-else 循环
Python while 循环
Python break 语句
Python Continue 语句
Python pass 语句
Python 嵌套循环

函数和模块

Python 函数
Python 默认参数
Python 关键字参数
Python 关键字专用参数
Python 位置参数
Python 仅限位置参数
Python 任意或可变长度参数
Python 变量作用域
Python 函数注释
Python 模块
Python 内置函数

字符串

Python 字符串
Python 字符串切片
Python 字符串修改
Python 字符串连接
Python 字符串格式化
Python 转义字符
Python 字符串方法
Python 字符串练习

列表

Python 列表
Python 访问列表项
Python 更改列表项
Python 添加列表项
Python 删除列表项
Python 循环列表
Python 列表推导式
Python 排序列表
Python 复制列表
Python 合并列表
Python 列表方法
Python 列表练习

元组

Python 元组
Python 访问元组项
Python 更新元组
Python 解包元组项
Python 循环元组
Python 合并元组
Python 元组方法
Python 元组练习

集合

Python 集合
Python 访问集合项
Python 添加集合项
Python 删除集合项
Python 循环集合
Python 合并集合
Python 复制集合
Python 集合运算符
Python 集合方法
Python 集合练习

字典

Python 字典
Python 访问字典项
Python 更改字典项
Python 添加字典项
Python 移除字典项
Python 字典视图对象
Python 循环字典
Python 复制字典
Python 嵌套字典
Python 字典方法
Python 字典练习

数组

Python 数组
Python 访问数组项
Python 添加数组项
Python 移除数组项
Python 循环数组
Python 复制数组
Python 反转数组
Python 排序数组
Python 合并数组
Python 数组方法
Python 数组练习

文件处理

Python 文件处理
Python 文件写入
Python 文件读取
Python 重命名和删除文件
Python 目录
Python 文件方法
Python 文件/目录方法
Python OS.Path 方法

面向对象编程

Python OOP 概念
Python 类和对象
Python 类属性
Python 类方法
Python 静态方法
Python 构造函数
Python 访问修饰符
Python 继承
Python 多态
Python 方法重写
Python 方法重载
Python 动态绑定
Python 动态类型
Python 抽象
Python 封装
Python 接口
Python 包
Python 内部类
Python 匿名类和对象
Python 单例类
Python 包装器类
Python 枚举
Python 反射

错误和异常

Python 语法错误
Python 异常处理
Python Try-Except
Python Try-Finally
Python 抛出异常
Python 异常链
Python 嵌套 try
Python 用户定义异常
Python 日志记录
Python 断言
Python 内置异常

多线程

Python 多线程
Python 线程生命周期
Python 创建线程
Python 启动线程
Python 合并线程
Python 命名线程
Python 线程调度
Python 线程池
Python 主线程
Python 线程优先级
Python 守护线程
Python 线程同步

同步

Python 线程间通信
Python 死锁
Python 中断线程

网络

Python 网络编程
Python 套接字编程
Python URL 处理
Python 泛型

杂项

Python Date and Time
Python math模块
Python 迭代器
Python 生成器
Python 闭包
Python 装饰器
Python 递归
Python 正则表达式
Python Pip
Python 数据库访问
Python 弱引用
Python 序列化
Python 模板技术
Python 输出格式化
Python 性能测量
Python 数据压缩
Python 通用网关接口
Python XML 处理
Python 用户界面(GUI)
Python 命令行参数
Python Docstrings
Python JSON
Python 发送电子邮件
Python 进一步扩展
Python 工具/实用程序
Python GUI

高级概念

Python 抽象基类
Python 自定义异常
Python 高阶函数
Python 对象的内部机制
Python 内存管理
Python 元类
Python 元编程
Python 模拟与桩
Python 猴子补丁
Python 信号处理
Python 类型提示
Python 进行自动化
Python Humanize包
Python 上下文管理器
Python 协程
Python 描述符
Python 内存泄漏
Python 不可变数据结构

Python 输出格式化


上一章 下一章

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

这些方法包括使用以下几种方式:

  • 字符串模运算符(%)
  • format() 方法
  • f-strings(格式化字符串字面量)
  • 模板字符串 此外,Python 的 "textwrap" 和 "pprint" 模块提供了文本包裹和漂亮打印数据结构的高级功能。

使用字符串模运算符(%)

我们可以使用字符串模运算符 % 来格式化输出。这个运算符是字符串特有的,并弥补了没有 C 风格 printf() 函数族的不足。格式化符号如 %d, %c, %f, 和 %s 在字符串中作为占位符使用,类似于 C 中的做法。

以下是一个简单的例子:

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

它将产生以下输出:

My name is Zara and weight is 21 kg!

使用 format() 方法

我们可以使用 format() 方法来格式化输出,这是在 Python 3.0 中引入并在 Python 2.6 和 2.7 中回退的功能。

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

语法

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

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

返回值

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

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

示例

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

它将产生以下输出:

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))

使用 F-Strings

F-strings 或格式化字符串字面量是格式化 Python 中字符串的一种简单、快速且易于阅读的方式。创建一个 f-string 是通过在字符串的开头添加一个 f 实现的。

在字符串内部,可以包含变量的占位符,它们由花括号 {} 包围。这些变量的值将在那些位置插入到字符串中。

示例

在这个例子中,变量 "name" 和 "age" 被插入到字符串中它们的占位符 "{name}" 和 "{age}" 所在的位置。F-strings 使得在字符串中包含变量值变得容易,无需使用 format() 方法或字符串连接。

name = 'Rajesh'
age = 23

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

它将产生以下输出:

My name is Rajesh and I am 23 years old

格式转换规则在 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

模板字符串

string 模块中的 Template 类提供了一种动态格式化字符串的替代方法。Template 类的一个好处是可以定制格式化规则。

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

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

示例

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)

它将产生以下输出:

My name is Rajesh and I am 23 years old

textwrap 模块

Python 的 textwrap 模块中的 wrap 类包含调整输入段落中的换行以格式化和包裹纯文本的功能。它有助于使文本格式良好且美观。

textwrap 模块具有以下便利函数:

  • textwrap.wrap(text, width=70):该函数将单个段落中的 text(一个字符串)包装成最多为 width 字符长的行。返回一个输出行的列表,没有最终的换行符。可选的关键字参数对应于 TextWrapper 类的实例属性。width 默认为 70。
  • textwrap.fill(text, width=70):该函数将单个段落中的 text 包装,并返回一个包含包装后的段落的单一字符串。

这两个方法内部创建了一个 TextWrapper 类的对象并调用其上的一个方法。由于实例没有重复使用,因此创建自己的 TextWrapper 对象会更有效率。

示例

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)

# 输出结果
for element in wrapped:
   print(element)

它将产生以下输出:

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 对象定义了以下属性:

  • width(默认:70):包装行的最大长度。
  • expand_tabs(默认:True):如果为真,则文本中的所有制表符将通过 expandtabs() 方法扩展为空格。
  • tabsize(默认:8):如果 expand_tabs 为真,则文本中的所有制表符将根据当前列和给定的制表符大小扩展为零或多个空格。
  • replace_whitespace(默认:True):如果为真,则在制表符扩展后但在包装之前,wrap() 方法将每个空白字符替换为单个空格。
  • drop_whitespace(默认:True):如果为真,则在包装后但在缩进前,删除每行开头和结尾的空白。然而,如果非空白字符紧随其后,则不会删除段落开头的空白。如果删除的空白占据整行,则整个行都会被删除。
  • initial_indent(默认:''):将附加到包装输出的第一行的字符串。
  • subsequent_indent(默认:''):将附加到所有包装输出行(除第一行外)的字符串。
  • fix_sentence_endings(默认:False):如果为真,TextWrapper 将尝试检测句子结尾并确保句子之间总是恰好有两个空格。对于使用等宽字体的文本来说,这通常是期望的。
  • break_long_words(默认:True):如果为真,则为了确保没有行超过 width,将会打断长度超过 width 的单词。如果为假,长单词不会被打断,有些行可能超过 width。
  • break_on_hyphens(默认:True):如果为真,包装将优先发生在空白处以及复合词中的连字符之后,这是英语中的惯例。如果为假,仅考虑空白作为可能的换行位置。

shorten() 函数

shorten() 函数压缩并截断给定的文本以适应给定的宽度。首先,文本中的空白会被压缩。如果它能适应 width,则直接返回。否则,尽可能多地组合单词,然后附加占位符。

示例

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))

它将产生以下输出:

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

pprint 模块

Python 标准库中的 pprint 模块使得 Python 数据结构的外观呈现出美观的形式。pprint 的名字代表 pretty printer。任何能被 Python 解释器正确解析的数据结构都会被优雅地格式化。

格式化的表达式尽可能保持在一行内,但如果长度超过了格式化宽度参数,则会折行。pprint 输出的一个独特特性是,在显示表示之前,字典会自动排序。

PrettyPrinter 类

pprint 模块定义了 PrettyPrinter 类。其构造函数采用以下格式:

语法

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

参数

  • indent — 定义每个递归级别的缩进。默认值是 1。
  • width — 默认值是 80。期望的输出受此值限制。如果长度大于 width,则会在多行中断开。
  • depth — 控制要打印的层级数量。
  • stream — 默认是标准输出设备 std.out。它可以接受任何流对象,如文件。
  • compact — 默认设置为 False。如果为真,只显示能适应 width 的数据。

PrettyPrinter 类定义了以下方法:

  • pprint() 方法

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

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

示例

下面的示例演示了 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 output
{'Dilip': ['English', 'Maths', 'Science'],
 'Kalpana': (50, 60, 70),
 'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}

pprint 模块还定义了与 PrettyPrinter 方法对应的方便函数 pprint() 和 pformat()。下面的例子使用了 pprint() 函数。

示例使用 pprint() 函数

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)

示例使用 pformat() 方法

下一个例子使用了 pformat() 方法以及 pformat() 函数。为了使用 pformat() 方法,首先设置了 PrettyPrinter 对象。在这两种情况下,使用正常的 print() 函数显示格式化的表示。

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)

上述代码的输出如下:

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 也可以与自定义类一起使用。在类中重写了 repr() 方法。__repr__() 方法在使用 repr() 函数时被调用。它是 Python 对象的官方字符串表示形式。当我们使用对象作为 print() 函数的参数时,它打印的是 repr() 函数的返回值。

示例

在此示例中,__repr__() 方法返回玩家对象的字符串表示形式:

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)

上述代码的输出如下:

{'virat': {'Tests': [140, 45, 39], 'ODI': [15, 122, 36, 67, 100, 49],
'T20': [78, 44, 12, 0, 23, 75]}}
上一章 下一章
阅读号二维码

关注阅读号

联系二维码

联系我们

© 2024 Yoagoa. All rights reserved.

粤ICP备18007391号

站点地图