Python 提供了多种字符串格式化方法,其中最常用的是 f-string(格式化字符串字面量)、str.format() 方法和传统的 % 格式化。它们都能将变量插入字符串中,但在语法、性能和功能上存在差异。选择合适的方式能让你的代码更清晰、高效。
f-string:现代推荐方式(Python 3.6+)
f-string 是目前最简洁、高效的字符串格式化方法。它在运行时直接求值表达式,并自动转换为字符串。
使用步骤:
- 在字符串前加
f或F前缀。 - 在花括号
{}内放入变量名或任意表达式。
name = "Alice"
age = 30
message = f"Hello, {name}! You are {age} years old."
print(message) # 输出: Hello, Alice! You are 30 years old.
你甚至可以在花括号内写完整表达式:
x = 10
y = 3
result = f"{x} * {y} = {x * y}"
print(result) # 输出: 10 * 3 = 30
支持格式控制,例如保留小数位:
price = 19.998
formatted = f"Price: {price:.2f}"
print(formatted) # 输出: Price: 20.00
str.format():灵活但稍显冗长
format() 方法通过位置或关键字参数替换占位符,适用于需要复用模板或兼容旧版本 Python(3.0+)的场景。
基本用法:
- 在字符串中使用
{}作为占位符。 - 调用
.format()并传入对应参数。
msg = "My name is {} and I am {} years old.".format("Bob", 25)
print(msg) # 输出: My name is Bob and I am 25 years old.
使用关键字参数提高可读性:
msg = "My name is {name} and I am {age} years old.".format(name="Charlie", age=40)
print(msg)
也支持格式说明符:
value = 3.14159
output = "Pi ≈ {:.3f}".format(value)
print(output) # 输出: Pi ≈ 3.142
% 格式化:传统 C 风格(已不推荐)
这是最早的格式化方式,模仿 C 语言的 printf,使用 %s、%d、%f 等占位符。
操作方式:
- 在字符串中插入
%s(字符串)、%d(整数)、%f(浮点数)等。 - 用
%运算符连接右侧的变量或元组。
name = "David"
score = 95
text = "Student: %s, Score: %d" % (name, score)
print(text) # 输出: Student: David, Score: 95
浮点数精度控制:
temp = 36.6789
display = "Temperature: %.2f°C" % temp
print(display) # 输出: Temperature: 36.68°C
⚠️ 注意:当只有一个参数时,仍需用元组形式 (value,),否则可能出错。
三种方式对比
| 特性 | f-string | str.format() |
% 格式化 |
|---|---|---|---|
| 引入版本 | Python 3.6 | Python 2.6 / 3.0 | Python 所有版本 |
| 性能 | 最快 | 中等 | 较慢 |
| 可读性 | 极高(变量直接嵌入) | 高(支持命名) | 低(符号易混淆) |
| 表达式支持 | 支持任意表达式 | 不支持(仅变量/属性) | 不支持 |
| 安全性 | 自动转义(相对安全) | 安全 | 易受注入攻击(如日志中) |
| 多行/复杂逻辑 | 清晰简洁 | 模板复用强 | 难以维护 |
如何选择?
- 新项目一律优先使用 f-string:语法直观、性能最优、功能最强。
- 若需兼容 Python < 3.6:退而使用
str.format()。 - 避免使用
%格式化:除非维护非常老的代码,否则不要主动采用。
注意边界情况:f-string 不能用于动态模板(如从配置文件读取格式字符串),此时应使用 format()。
# 错误示例:f-string 无法动态构造
template = "{user} logged in at {time}" # 来自外部
# 不能写成 f"{template}" —— 这不会解析内部占位符
# 正确做法:
result = template.format(user="admin", time="10:00")
对于大多数日常开发,直接写 f-string 即可覆盖 95% 的需求。

暂无评论,快来抢沙发吧!