Python 字符串格式化全攻略:从基础到 f-string 高级应用105


作为一名专业的程序员,高效且清晰地处理字符串是日常工作中不可或缺的技能。在 Python 中,字符串不仅仅是文本序列,它们还承载着数据展示、日志输出、用户界面交互等多种功能。因此,掌握 Python 字符串的“修饰”(即格式化)技巧,能极大地提升代码的可读性、可维护性和功能性。本文将深入探讨 Python 中字符串格式化的多种方法,从经典的 `%` 运算符到现代的 f-string,旨在帮助你全面掌握并选择最适合你场景的字符串修饰方式。

Python 语言在字符串格式化方面经历了显著的演变,提供了多种功能强大且语法优雅的工具。了解这些工具的演进和各自的优缺点,将使你能够根据项目需求和Python版本做出明智的选择。

一、经典字符串格式化:`%` 运算符(Python 2 风格)

在 Python 早期版本中,`%` 运算符是主要的字符串格式化工具,其语法和行为类似于 C 语言的 `printf` 函数。尽管在现代 Python 代码中已不推荐作为首选,但了解它对于阅读遗留代码仍有必要。

1. 基本用法


`%` 运算符通过在字符串中插入格式说明符(如 `%s`、`%d`、`%f` 等)来指定待格式化的数据类型和位置。操作符右侧可以是一个元组(按顺序对应格式说明符)或一个字典(通过键名对应)。```python
# 使用元组
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))
# 输出: My name is Alice and I am 30 years old.
# 使用字典(命名占位符)
data = {"city": "New York", "temperature": 25.5}
print("The temperature in %(city)s is %(temperature).1f degrees Celsius." % data)
# 输出: The temperature in New York is 25.5 degrees Celsius.
```

2. 常用格式说明符



`%s`: 字符串 (string)
`%d`: 有符号十进制整数 (decimal integer)
`%f`: 浮点数 (float)
`%x` / `%X`: 十六进制整数 (hexadecimal integer)
`%o`: 八进制整数 (octal integer)
`%e` / `%E`: 科学计数法 (scientific notation)

3. 宽度与精度控制


可以在格式说明符中添加数字来控制字段的宽度和浮点数的精度。```python
# 字段宽度和精度
pi = 3.1415926535
print("Pi with 2 decimal places: %.2f" % pi) # 输出: Pi with 2 decimal places: 3.14
print("Pi with total width 10, 4 decimal places: %10.4f" % pi) # 输出: Pi with total width 10, 4 decimal places: 3.1416
# 左对齐(负号)
product = "Laptop"
price = 999.99
print("Product: %-10s | Price: %.2f" % (product, price)) # 输出: Product: Laptop | Price: 999.99
```

4. 优缺点



优点: 语法简洁,对于熟悉 C 语言 `printf` 的开发者来说易于上手。
缺点: 可读性差,特别是当有多个占位符时容易出错(类型和顺序不匹配)。不支持对象格式化,且灵活性不足。

二、`()` 方法(Python 3 推荐)

`()` 方法在 Python 2.6 引入,并在 Python 3 中成为字符串格式化的首选方式,它提供了比 `%` 运算符更强大、更灵活且更可读的机制。

1. 基本用法


使用 `{}` 作为占位符,然后调用字符串的 `format()` 方法,传入要替换的值。这些值可以是位置参数或关键字参数。```python
# 位置参数
print("My name is {} and I am {} years old.".format("Bob", 25))
# 输出: My name is Bob and I am 25 years old.
# 索引位置参数
print("{0} is learning {1} from {2}.".format("Alice", "Python", "Guru"))
# 输出: Alice is learning Python from Guru.
# 关键字参数
print("User: {username}, Email: {email}".format(username="charlie", email="charlie@"))
# 输出: User: charlie, Email: charlie@
# 混合使用
print("The {product} costs ${price:.2f}".format(product="Book", price=29.99))
# 输出: The Book costs $29.99
```

2. 格式化迷你语言 (Format Specifier Mini-Language)


`()` 最强大的特性之一是其内置的格式化迷你语言,可以在 `{}` 内部通过 `:` 后跟指令来控制输出的样式。

a. 对齐与填充


使用 `` (右对齐), `^` (居中) 指定对齐方式,并可以在符号前指定填充字符。```python
text = "Hello"
print("'{:10}'".format(text)) # 右对齐,宽度10,默认空格填充: ' Hello'
print("'{:^10}'".format(text)) # 居中对齐,宽度10: ' Hello '
print("'{:*^10}'".format(text)) # 居中对齐,宽度10,*填充: '*Hello'
```

b. 数字格式化



精度: `:.nf` 控制浮点数小数位数。
千位分隔符: `,` 用于数字的千位分隔。
符号: `+` (总是显示符号), `-` (只显示负号), ` ` (正数显示空格)
进制: `b` (二进制), `d` (十进制), `o` (八进制), `x` / `X` (十六进制)

```python
value = 1234567.89123
print("Float with 2 decimal places: {:.2f}".format(value)) # 输出: 1234567.89
print("Number with thousands separator: {:,}".format(value)) # 输出: 1,234,567.89123
print("Positive number with sign: {:+d}".format(100)) # 输出: +100
print("Negative number with sign: {: d}".format(-200)) # 输出: -200
print("Binary: {:b}, Hex: {:X}".format(10, 255)) # 输出: Binary: 1010, Hex: FF
```

c. 日期时间格式化


虽然 `datetime` 模块有其自身的 `strftime` 方法,但 `()` 可以结合 `datetime` 对象使用。```python
from datetime import datetime
now = ()
print("Current date and time: {:%Y-%m-%d %H:%M:%S}".format(now))
# 输出: Current date and time: 2023-10-27 10:30:00 (示例日期时间)
```

3. 优缺点



优点: 极高的灵活性和可读性,通过迷你语言支持各种复杂的格式化需求。参数通过名称或索引传递,避免了 `%` 运算符的顺序错误。支持自定义对象的格式化(通过 `__format__` 方法)。
缺点: 对于非常简单的场景,语法可能显得略微冗长。

三、f-string (格式化字符串字面量)(Python 3.6+ 现代推荐)

f-string 是在 Python 3.6 中引入的一种新的字符串格式化方式,它以其简洁、高效和可读性迅速成为最受欢迎的方法。f-string 本质上是 `()` 的语法糖,它允许你将表达式直接嵌入到字符串字面量中,并在运行时进行求值和格式化。

1. 基本用法


在字符串前加上 `f` 或 `F`,然后在 `{}` 内部直接放入变量名或任意有效的 Python 表达式。```python
name = "Charlie"
age = 35
print(f"My name is {name} and I am {age} years old.")
# 输出: My name is Charlie and I am 35 years old.
# 直接嵌入表达式
x = 10
y = 20
print(f"The sum of {x} and {y} is {x + y}.")
# 输出: The sum of 10 and 20 is 30.
# 调用函数
def get_status():
return "active"
print(f"User status: {get_status()}")
# 输出: User status: active
```

2. 结合格式化迷你语言


f-string 完全支持 `()` 的格式化迷你语言,使得复杂的格式化变得异常简洁。```python
pi = 3.1415926535
product_name = "Keyboard"
price = 79.95
stock = 1234567
print(f"Pi with 2 decimal places: {pi:.2f}") # 输出: Pi with 2 decimal places: 3.14
print(f"Product: {product_name:

2025-10-16


上一篇:Python函数交互的艺术:深度解析函数调用、嵌套、传递与返回的奥秘

下一篇:Python文件读取与字符串处理:从基础到高级的全面指南