Python 中的字符串格式化曾经有点麻烦。必须在 % 运算符、str.format() 或字符串连接的组合之间进行选择,才能将变量注入字符串中。幸运的是,Python 3.6 引入了 f-strings(格式化字符串文字),这是一种使代码更简洁、更具可读性和更高效的强大方法。
什么是 f 字符串?
f-string 是前缀为字母 f 的字符串文本,允许在大括号 {} 内包含表达式,这些表达式在运行时进行计算。这使得包含变量值、执行计算甚至调用函数变得容易 - 所有这些都直接在字符串中完成。
下面是一个基本示例:
name = "Alice"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message)
输出:
My name is Alice and I am 30 years old.
f 字符串的美妙之处在于它们的简单性:您只需在开始引号前加上一个 f,然后使用 {} 将值直接插入到字符串中。
f 字符串的优点
1. 可读性
与旧的格式设置方法相比,F 字符串更具可读性,因此很容易看到每个变量或表达式的去向。
2. 简洁
F 字符串消除了对 str.format() 等详细方法调用的需要。您的字符串更简洁,代码更短。
3. 灵活性
可以在 {} 中嵌入任何有效的 Python 表达式,包括算术运算或函数调用。
4. 类型提示集成
使用类型提示时,f-strings 可以帮助确保变量的格式与其预期类型一致:
def greet(user: str) -> str:
return f"Hello, {user}!"
print(greet("Alice"))
类型提示与 f 字符串相结合,有助于使代码自文档化且可读。
使用 f 字符串的示例
1. 使用 f 字符串格式化变量
假设有一些表示产品的变量:
product = "Laptop"
price = 999.99
formatted = f"The {product} costs ${price:.2f}."
print(formatted)
输出:
The Laptop costs $999.99.
此处,:.2f 指定价格的格式应为小数点后两位 — 非常适合显示货币值。
2. 在 f 字符串中执行计算
您可以直接在 f 字符串中包含计算:
length = 5
width = 3
area_message = f"The area of the rectangle is {length * width} square units."
print(area_message)
输出:
The area of the rectangle is 15 square units.
3. 使用格式说明符
F 字符串支持各种格式说明符来控制输出:
# Right-aligned text with padding
print(f"|{'Hello':>10}|")
# Left-aligned text
print(f"|{'World':<10}|")
# Center-aligned text
print(f"|{'Center':^10}|")
# Formatting numbers
num = 1234.56789
print(f"Number with commas: {num:,.2f}")
print(f"Percentage: {0.756:.1%}")
输出:
| Hello|
|World |
| Center |
Number with commas: 1,234.57
Percentage: 75.6%
4. 使用 f 字符串进行调试
使用 {var=} 语法进行快速调试:
x = 42
print(f"{x=}")
输出:
x=42
高级功能
1. 多行 f 字符串
对于较长的字符串,请使用多行 f 字符串以获得更好的可读性:
name = "Alice"
city = "Wonderland"
message = (
f"Hello, {name}!\n"
f"Welcome to {city}. We hope you enjoy your stay."
)
print(message)
2. 处理特殊字符
如果你需要在 f 字符串中包含大括号 {},只需将它们加倍即可:
result = f"To include curly braces, use double braces: {{ and }}."
print(result)
输出:
To include curly braces, use double braces: { and }.
与模板字符串的比较
虽然 f-strings 通常更快、可读性更强,但 string 模块中的 Python 模板字符串在处理不受信任的 input 时提供了更好的安全性。
from string import Template
user_input = "Alice"
template = Template("Hello, $name!")
message = template.substitute(name=user_input)
print(message)
模板字符串更安全,因为它们只允许变量替换,不支持任意表达式。在处理用户生成的内容以防止注入攻击时,这可能是一个显著的优势。
安全注意事项
F 字符串允许任意表达式,如果您直接合并用户输入,这可能会有风险:
user_input = "__import__('os').system('ls')"
# Dangerous! Avoid using f-strings with untrusted input:
# print(f"User input: {user_input}")
相反,在将用户输入包含在 f 字符串中之前,请使用 Template strings 或对其进行清理,以避免潜在的安全漏洞。
性能比较
f 弦的主要优点之一是它们的性能。让我们将 f 字符串与 % 运算符、str.format() 和模板字符串进行比较:
import timeit
name = "Alice"
age = 30
f_string_time = timeit.timeit("f'{name} is {age} years old'", globals=globals(), number=1000000)
format_time = timeit.timeit("'{} is {} years old'.format(name, age)", globals=globals(), number=1000000)
percent_time = timeit.timeit("'%s is %d years old' % (name, age)", globals=globals(), number=1000000)
template_time = timeit.timeit("Template('$name is $age years old').substitute(name=name, age=age)",
globals=globals(), number=1000000)
print(f"f-string: {f_string_time:.6f}s, str.format(): {format_time:.6f}s, %-formatting: {percent_time:.6f}s, Template: {template_time:.6f}s")
典型输出:
f-string: 0.085123s, str.format(): 0.121456s, %-formatting: 0.130567s, Template: 0.155789s
结论:f 字符串是最快的,但如果安全是一个问题(例如,处理用户输入),请考虑使用模板字符串。
要避免的陷阱
1. 仅限 Python 3.6+
F 字符串仅在 Python 3.6 及更高版本中可用。如果您使用的是旧版本,则需要使用其他格式设置方法。
2. 保持表达式简单
避免在 {} 中使用过于复杂的表达式以提高可读性:
# Instead of this:
formatted = f"The result is {((10 ** 2 + 5) / 3):.2f}"
# Do this:
result = (10 ** 2 + 5) / 3
formatted = f"The result is {result:.2f}"
3. 谨慎对待用户输入
切勿直接将 f 字符串与不受信任的输入一起使用。使用 Template strings 以获得更安全的方法。
结论
F 字符串提供了一种现代、可读且简洁的方式来在 Python 中格式化字符串。它们功能强大、灵活且性能卓越,是大多数使用案例的理想选择。但是,对于涉及用户输入的方案,请考虑使用 Template strings 以避免安全问题。