杰瑞科技汇

Python print格式化输出有哪些常用方法?

下面我将详细介绍这些方法,并按照推荐顺序进行说明。

Python print格式化输出有哪些常用方法?-图1
(图片来源网络,侵删)

核心概念:print 函数的基本用法

回顾一下 print 函数的基本语法:

print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  • value1, value2, ...: 你想打印的一个或多个值。
  • sep: 多个值之间的分隔符,默认是一个空格。
  • end: 打印结束后添加的字符,默认是换行符 \n
  • file: 输出的目标文件,默认是 sys.stdout(即标准输出,也就是你的控制台)。
  • flush: 是否强制刷新输出缓冲区。

格式化输出的核心在于如何构造 value 这个参数。


f-strings (格式化字符串字面量) - 现代、推荐

这是 Python 3.6+ 引入的最新、最简洁、最易读的格式化方法,它使用前缀 fF 来定义字符串,并在字符串内部使用 来嵌入表达式或变量。

语法:

Python print格式化输出有哪些常用方法?-图2
(图片来源网络,侵删)
f'...{expression}...'

特点:

  • 简洁易读:语法非常直观,代码和最终输出的结构几乎一致。
  • 性能高:在底层,f-strings 被优化为速度最快的格式化方法。
  • 功能强大:可以在 内部直接进行表达式计算、调用函数等。

示例:

name = "Alice"
age = 30
score = 95.5
# 1. 基本变量替换
print(f"Hello, my name is {name}.")
# 输出: Hello, my name is Alice.
# 2. 在 {} 中进行计算和调用函数
print(f"Next year, I will be {age + 1} years old.")
# 输出: Next year, I will be 31 years old.
# 3. 格式化数字(保留小数位数)
print(f"My average score is {score:.2f}.")
# 输出: My average score is 95.50.
# 4. 格式化数字(科学计数法、千位分隔符)
large_num = 1000000
print(f"The population is {large_num:,}.")
# 输出: The population is 1,000,000.
print(f"The value is {large_num:e}.")
# 输出: The value is 1.000000e+06.
# 5. 格式化字符串(宽度、对齐)
print(f"Name: {name:>10}")  # 右对齐,总宽度为10
# 输出: Name:      Alice
print(f"Name: {name:<10}")  # 左对齐,总宽度为10
# 输出: Name: Alice      
print(f"Name: {name:^10}")  # 居中对齐,总宽度为10
# 输出: Name:   Alice   
# 6. 使用字典
person = {"name": "Bob", "city": "New York"}
print(f"{person['name']} lives in {person['city']}.")
# 输出: Bob lives in New York.

格式说明符 (Format Specifier): 在 内部, 后面可以跟格式说明符,其通用语法为: {field_name!conversion:format_spec}

  • format_spec 的结构:[[fill]align][sign][#][0][width][,][.precision][type]
    • align: < (左对齐), > (右对齐), ^ (居中), (数字符号放在填充符之后)
    • sign: (正负号都显示), (只显示负号, 默认), ` ` (正数前加空格, 负数加负号)
    • width: 总宽度
    • precision: 小数点后的精度
    • type: f (浮点数), d (十进制整数), x (十六进制), s (字符串) 等

str.format() 方法 - 灵活、通用

这是 Python 2.6+ 和 Python 3.x 都支持的方法,比 运算符更灵活、更易读。

Python print格式化输出有哪些常用方法?-图3
(图片来源网络,侵删)

语法:

'...{}...'.format(value)
'...{0}...{1}...'.format(value0, value1)

特点:

  • 通过 作为占位符,可以按位置或关键字传递参数。
  • 功能强大,支持 f-string 中的大部分格式化选项。

示例:

name = "Charlie"
age = 25
# 1. 按位置传递参数
print("Hello, {}. You are {} years old.".format(name, age))
# 输出: Hello, Charlie. You are 25 years old.
# 2. 使用关键字参数
print("Hello, {n}. You are {a} years old.".format(n=name, a=age))
# 输出: Hello, Charlie. You are 25 years old.
# 3. 访问对象的属性/索引
class Person:
    def __init__(self, name):
        self.name = name
p = Person("David")
print("Hello, {p.name}!".format(p=p))
# 输出: Hello, David!
# 4. 格式化选项(与 f-string 类似,写在 {} 内部)
pi = 3.14159
print("Pi is approximately {:.2f}.".format(pi))
# 输出: Pi is approximately 3.14.

运算符 (旧式字符串格式化) - 已过时

这是 Python 早期版本(如 Python 2)中使用的格式化方法,类似于 C 语言中的 printf

语法:

'%s %d %f' % (value1, value2, value3)

特点:

  • 语法略显冗长和复杂,尤其是处理多个变量时。
  • 容易出错,例如参数顺序错误或类型不匹配。
  • 官方文档已将其标记为过时,不推荐在新代码中使用。

示例:

name = "Eve"
age = 28
print("Hello, %s. You are %d years old." % (name, age))
# 输出: Hello, Eve. You are 28 years old.
# 格式化选项
print("Pi is approximately %.2f." % 3.14159)
# 输出: Pi is approximately 3.14.

Template 字符串 - 简单、安全

string 模块中的 Template 类提供了一种更简单的格式化方法,适用于简单的场景,它使用 作为占位符。

语法:

from string import Template
t = Template('...$var...')
result = t.substitute(var=value)

特点:

  • 语法非常简单。
  • 安全性高:当格式化字符串来自不可信的来源(如用户输入)时,Templatestr.format()f-string 更安全,因为它只支持基本的变量替换,不会执行任意代码。
  • 功能最弱,不支持复杂的格式化选项。

示例:

from string import Template
name = "Frank"
age = 40
# 使用 $ 作为占位符
t = Template("Hello, $name. You are $age years old.")
print(t.substitute(name=name, age=age))
# 输出: Hello, Frank. You are 40 years old.
# 如果缺少参数,会引发 KeyError
# t.substitute(name=name) # KeyError: 'age'

总结与对比

方法 Python 版本 可读性 功能 安全性 推荐度
f-strings 6+ 极高 非常强大 强烈推荐
str.format() 6+, 3.x 强大 推荐用于兼容旧代码
运算符 所有 较弱 不推荐 (已过时)
Template 所有 极高 适用于用户输入等简单场景

最佳实践建议

  1. 首选 f-strings:如果你的代码运行在 Python 3.6 或更高版本,请毫不犹豫地使用 f-strings,它结合了可读性、性能和功能于一体,是现代 Python 编程的标准。

  2. 次选 str.format():如果你需要编写兼容旧版本 Python (如 3.5 或更早) 的代码,或者你的格式化逻辑非常复杂且需要从外部构建字符串模板,str.format() 是一个很好的选择。

  3. 避免使用 运算符:除非你在维护非常古老的代码库,否则不要再使用 来进行新的格式化。

  4. 考虑 Template 的安全场景:当你需要处理来自不可信来源的字符串模板,并且希望绝对避免代码注入风险时,Template 是最安全的选择。

分享:
扫描分享到社交APP
上一篇
下一篇