5 个 Python f-字符串技巧
Python 的 f 字符串不仅仅是将变量嵌入字符串的便捷方式——它们是简化代码并提高可读性的强大工具。自 Python 3.6 引入以来,f 字符串因其灵活性和效率迅速成为开发者的最爱。在本文中,我们将探讨五个非常实用的 f 字符串技巧,每个 Python 开发者都应该将其纳入工具箱。
基本 f-字符串用法:简洁至上
在深入高级技巧之前,回顾一下基础知识。f-字符串允许您通过使用花括号 {} 直接在字符串中嵌入变量和表达式。以下是旧 .format() 方法与 f-字符串的快速比较:
旧方法:
name = "Alice"
age = 30
print("Hello, my name is {} and I am {} years old.".format(name, age))
F-字符串方法:
name = "Alice"
age = 30
print(f"Hello, my name is {name} and I am {age} years old.")
F-字符串不仅更简洁,而且更容易阅读。此外,它们支持嵌入表达式:
print(f"In two years, I’ll be {age + 2} years old.")
2. 数字格式化:整洁精确
f-字符串在格式化数字方面表现出色。无论是四舍五入小数还是添加千位分隔符,它们都能满足你的需求:
四舍五入小数
price = 1234.56789
print(f"Price: {price:.2f}") # Output: Price: 1234.57
添加逗号以提高可读性:
large_number = 1234567
print(f"Formatted: {large_number:,}") # Output: Formatted: 1,234,567
甚至可以将这些格式选项组合起来:
print(f"Rounded and formatted: {price:,.2f}") # Output: Rounded and formatted: 1,234.57
3. 日期格式化:驯服 datetime 对象
与 datetime 对象一起工作通常会导致输出冗长且杂乱。f-string 允许您格式化日期以适应您的需求:
from datetime import datetime
now = datetime.now()
print(f"Today is: {now:%Y-%m-%d}") # Output: Today is: 2025-02-07
可以重新排列格式以符合您的喜好:
print(f"Custom format: {now:%d/%m/%Y}") # Output: Custom format: 07/02/2025
4. 文本对齐:非常适合终端输出
需要终端中整洁地格式化数据?F-字符串支持使用<、> 和^进行文本对齐
name = "Alice"
print(f"|{name:<10}|") left-align printfname:>10}|") # Right-align
print(f"|{name:^10}|") # Center-align
对于表格数据,这尤其有用:
data = [
("Alice", 30, "Engineer"),
("Bob", 25, "Designer"),
("Charlie", 35, "Manager")
]
print(f"{'Name':<10}{'Age':<5}{'Occupation':<10}")
for name, age, job in data:
print(f"{name:<10}{age:<5}{job:<10}")
这输出了一个整齐对齐的表格。
5. 使用 f-字符串进行调试:快速直观
调试通常需要打印变量名及其值。使用 f 字符串,这变得轻而易举:
x = 10
y = 5
print(f"{x=}, {y=}, {x + y=}")
# Output: x=10, y=5, x + y=15
The {var=} 语法同时打印变量名和其值,节省您的时间,并使调试变得更加简单。
也可以嵌入复杂表达式:
print(f"{(x + y) ** 2=}") # Output: (x + y) ** 2=225