Python 字符串格式化:占位符的进阶指南388


Python 提供了多种强大的字符串格式化方法,其中占位符(placeholder)是最常用且易于理解的一种。它允许你在字符串中预留位置,然后用变量或表达式的值来填充这些位置,从而动态生成字符串。本文将深入探讨 Python 中的字符串占位符,涵盖各种方法及其优缺点,并提供最佳实践建议。

1. 旧式字符串格式化 (% 操作符)

这是 Python 早期版本中常用的方法,使用 `%` 操作符进行格式化。它类似于 C 语言的 printf 函数。 `%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.
price = 99.99
print("The price is %.2f dollars." % price) # 输出: The price is 99.99 dollars.
```

优点:简洁,易于理解,在简单场景下非常高效。

缺点:可读性差,尤其是在处理多个变量时;不支持更复杂的格式化需求;容易出错,例如参数数量不匹配。

2. `()` 方法

`()` 方法是 Python 2.6+ 版本引入的,比旧式格式化更加灵活和强大。它使用花括号 `{}` 作为占位符,并通过参数索引或参数名来指定要填充的值。

```python
name = "Bob"
age = 25
city = "New York"
print("My name is {0}, I am {1} years old, and I live in {2}.".format(name, age, city)) # 输出: My name is Bob, I am 25 years old, and I live in New York.
print("My name is {name}, I am {age} years old, and I live in {city}.".format(name=name, age=age, city=city)) # 使用参数名
```

优点:可读性更好,更易于维护;支持更复杂的格式化需求;避免了参数数量不匹配的问题;允许重复使用参数。

缺点:对于简单的格式化,可能略显冗长。

3. f-strings (Formatted String Literals)

f-strings 是 Python 3.6+ 版本引入的,它是目前 Python 中最推荐的字符串格式化方法。它以 `f` 或 `F` 开头,在花括号 `{}` 中直接嵌入表达式,并将其值转换为字符串。

```python
name = "Charlie"
age = 40
print(f"My name is {name}, and I am {age} years old.") # 输出: My name is Charlie, and I am 40 years old.
price = 123.456
print(f"The price is {price:.2f} dollars.") # 格式化输出,保留两位小数
print(f"The price is {price:10.2f} dollars.") # 设置宽度为10,右对齐
print(f"The price is {price:>10.2f} dollars.") # 设置宽度为10,右对齐
print(f"The price is {price:

2025-06-18


上一篇:Python 列表转换为字符串:方法详解与性能比较

下一篇:Python字符串到数字的转换:详解与最佳实践