杰瑞科技汇

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

我们将按照演进顺序来介绍,这样更容易理解它们的设计初衷和区别。

使用 运算符 (旧式字符串格式化)

这是 Python 早期版本(如 Python 2)中非常流行的方式,类似于 C 语言中的 printf 函数,它使用 作为占位符。

常用占位符:

  • %s:字符串
  • %d:十进制整数
  • %f:浮点数
  • %.2f:保留两位小数的浮点数
  • %x:十六进制整数

示例:

name = "Alice"
age = 30
score = 95.5
# 基本用法
print("My name is %s." % name)
# 输出: My name is Alice.
# 多个变量需要格式化,需要用元组 (tuple) 括起来
print("My name is %s, I am %d years old." % (name, age))
# 输出: My name is Alice, I am 30 years old.
# 格式化浮点数
print("My score is %f." % score)
# 输出: My score is 95.500000.
# 指定小数位数
print("My score is %.2f." % score)
# 输出: My score is 95.50.

评价:简单直观,但对于复杂的格式化,代码会变得难以阅读和维护,特别是当变量数量很多时。


str.format() 方法 (Python 2.6+ 推荐方式)

这是对 运算符的重大改进,它使用 作为占位符,通过 .format() 方法来填充内容,这种方式更灵活、更易读。

示例:

name = "Bob"
age = 25
score = 88.888
# 基本用法:按顺序填充
print("My name is {}.".format(name))
# 输出: My name is Bob.
# 使用数字索引来指定填充位置
print("{0} is {1} years old, and {0}'s score is {2}.".format(name, age, score))
# 输出: Bob is 25 years old, and Bob's score is 88.888.
# 使用关键字参数,可读性更高
print("My name is {n}, I am {a} years old.".format(n=name, a=age))
# 输出: My name is Bob, I am 25 years old.
# 格式化浮点数
print("Score: {:.2f}".format(score))
# 输出: Score: 88.89
# 格式化整数,补零
print("ID: {:05d}".format(42))
# 输出: ID: 00042

评价:比 运算符更清晰、更强大,是 Python 3.5 之前官方推荐的方式。


f-strings (格式化字符串字面量) (Python 3.6+ 现代首选)

这是目前最新、最简洁、最高效的字符串格式化方法,它通过在字符串前加上 fF 来创建,并在 中直接嵌入变量或表达式。

示例:

name = "Charlie"
age = 35
score = 99.9
# 基本用法:直接在 {} 中写变量名
print(f"My name is {name}.")
# 输出: My name is Charlie.
# 可以在 {} 中直接进行数学运算或调用函数
print(f"Next year, I will be {age + 1} years old.")
# 输出: Next year, I will be 36 years old.
# 格式化浮点数,语法与 .format() 类似
print(f"Score: {score:.2f}")
# 输出: Score: 99.90
# 格式化整数,补零
print(f"ID: {42:05d}")
# 输出: ID: 00042
# 使用字典
person = {"name": "David", "age": 28}
print(f"Name: {person['name']}, Age: {person['age']}")
# 输出: Name: David, Age: 28
# 调用对象的方法
class User:
    def __init__(self, name):
        self.name = name
    def get_greeting(self):
        return f"Hello, I'm {self.name}"
user = User("Eve")
print(f"{user.get_greeting()}")
# 输出: Hello, I'm Eve

评价强烈推荐! f-strings 语法简洁、可读性极高、执行速度快,是现代 Python 开发中格式化字符串的首选方法。


print() 函数的其他重要参数

除了格式化字符串本身,print() 函数还有几个非常有用的参数:

sep (分隔符)

默认情况下,print() 会用空格 ` 作为多个输出项之间的分隔符,你可以用sep` 参数来修改它。

print("apple", "banana", "cherry")
# 输出: apple banana cherry
print("apple", "banana", "cherry", sep=", ")
# 输出: apple, banana, cherry
print("A", "B", "C", sep="-")
# 输出: A-B-C

end (结尾符)

默认情况下,print() 会在输出末尾添加一个换行符 \n,你可以用 end 参数来修改它,使其不换行或添加其他内容。

# 不换行打印,常用于进度条或循环中
for i in range(3):
    print(f"Processing item {i}", end="... ")
# 输出: Processing item 0... Processing item 1... Processing item 2... 
# 指定结尾为其他字符
print("Hello", end="***\n")
print("World", end="***\n")
# 输出:
# Hello***
# World***

file (输出位置)

默认情况下,print() 将输出到标准输出流(通常是你的终端/控制台),你可以使用 file 参数将其重定向到其他文件对象。

# 创建一个文件对象
with open("output.txt", "w", encoding="utf-8") as f:
    # 将 "Hello, File!" 写入到 output.txt 文件中,而不是打印到屏幕
    print("Hello, File!", file=f)
print("内容已写入 output.txt 文件。")

总结与推荐

方法 语法 优点 缺点 推荐度
运算符 "My name is %s" % "Alice" 简单、历史悠久 复杂时难以阅读,功能有限 ⭐ (仅维护旧代码)
str.format() "My name is {}".format("Alice") 灵活、可读性好、功能强大 比 f-strings 稍显冗长 ⭐⭐ (兼容性好)
f-strings f"My name is {'Alice'}" 简洁、易读、高效、功能强大 需要 Python 3.6+ ⭐⭐⭐⭐⭐ (强烈推荐)

最终建议:

  • 如果你使用的是 Python 3.6 或更高版本,请毫不犹豫地使用 f-strings。 它是当前最佳实践。
  • 如果你正在维护使用旧版 Python(3.5 或更早)的项目,或者需要代码兼容这些版本,str.format() 是一个很好的选择。
  • 尽量避免在新代码中使用 运算符,除非有特殊的历史遗留原因。
分享:
扫描分享到社交APP
上一篇
下一篇