网站首页 > 技术文章 正文
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 以避免安全问题。
猜你喜欢
- 2025-06-18 Python小游戏——“石头剪刀布”(python石头剪刀布游戏怎么写)
- 2025-06-18 3.2数据类型和变量赋值(JAVA程序员改行Python当天入门教程)
- 2025-06-18 GESP第六次认证真题解析C++、Python直播预告
- 2025-06-18 每周一个 Python 模块 | fnmatch(python一周的星期几)
- 2025-06-18 fsociety,一个非常厉害的 Python 库!
- 2025-06-18 python学习笔记之f-string,小白的成长历程
- 2025-06-18 Python基础:f-string不同数据类型的格式化选项,终极指南!
- 2025-06-18 在 Python 中使用 f-String 格式化字符串
- 2025-06-18 Python中f-string用法(for char in python string)
- 2025-06-18 python中format函数和f-string详解
- 07-06Python学不会来打我(19)循环语句while/for的使用方法与实战案例
- 07-06python入门-day5-循环语句(python循环语句总结)
- 07-06Python循环:重复的力量(python中如何重复循环程序)
- 07-06编程小白学做题:Python 的经典编程题及详解,附代码和注释(一)
- 07-06python 简述列表推导式和生成器(python列表举例)
- 07-06Python列表推导式:让你的代码优雅如诗!
- 07-06Python中while循环详解(python中while循环的执行过程)
- 07-06Python自学|while循环的使用方法|99乘法口诀表倒着打印
- 274℃Python短文,Python中的嵌套条件语句(六)
- 272℃python笔记:for循环嵌套。end=""的作用,图形打印
- 270℃PythonNet:实现Python与.Net代码相互调用!
- 265℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 265℃Python实现字符串小写转大写并写入文件
- 124℃原来2025是完美的平方年,一起探索六种平方的算吧
- 106℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 104℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
-
- Python学不会来打我(19)循环语句while/for的使用方法与实战案例
- python入门-day5-循环语句(python循环语句总结)
- Python循环:重复的力量(python中如何重复循环程序)
- 编程小白学做题:Python 的经典编程题及详解,附代码和注释(一)
- python 简述列表推导式和生成器(python列表举例)
- Python列表推导式:让你的代码优雅如诗!
- Python中while循环详解(python中while循环的执行过程)
- Python自学|while循环的使用方法|99乘法口诀表倒着打印
- 用while循环做一个九九乘法表(用while循环和for循环分别输出九九乘法表)
- 怎么用三种代码写「九九乘法表」(九九乘法表的代码怎么写)
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)