目录
什么是 f-string
f-string 是 Python 3.6 引入的一种字符串格式化方法。通过在字符串前加 f 或 F 前缀,直接在 {} 中嵌入变量或表达式。相比传统的 % 格式化和 str.format() 方法,f-string 执行速度更快,并且支持复杂的格式化操作,如数字精度控制、对齐、日期格式化等,甚至可用于代码调试。
基础用法
变量插值
name: str = "张三" age: int = 25 print(f"我是{name},今年{age}岁。") # 输出: 我是张三,今年25岁。
表达式嵌入
x, y = 10, 20 print(f"{x} + {y} = {x + y}") # 输出: 10 + 20 = 30
调用函数
def square(n): return n ** 2 num = 5 print(f"{num} 的平方等于 {square(num)}") # 输出: 5 的平方等于 25
数字格式化
千位分隔符
money = 1000000000 print(f"{money:,} 元") # 输出: 1,000,000,000 元 print(f"{money:_} 元") # 输出: 1_000_000_000 元
控制小数位数
pi = 3.1415926535 print(f"四舍五入到两位: {pi:.2f}") # 输出: 四舍五入到两位: 3.14 print(f"四舍五入到整数: {pi:.0f}") # 输出: 四舍五入到整数: 3
百分比转换
ratio = 0.75 print(f"百分比: {ratio:.2%}") # 输出: 百分比: 75.00%
科学计数法
value = 0.0001234 print(f"科学计数法: {value:.2e}") # 输出: 科学计数法: 1.23e-04
文本对齐与填充
填充对齐
text = "Python" print(f"填充10字符左对齐: '{text:<10}'") # 左对齐 # 输出: 填充20字符左对齐: 'Python ' print(f"填充10字符右对齐: '{text:>10}'") # 右对齐 # 输出: 填充20字符右对齐: ' Python' print(f"填充10字符居中对齐: '{text:^10}'") # 居中对齐 # 输出: 填充20字符居中对齐: ' Python '
自定义填充字符
text = "Python" print(f"{text:_^20}") # 输出: _______Python_______ print(f"{text:#^20}") # 输出: #######Python#######
日期时间格式化
from datetime import datetime now = datetime.now() print(f"日期: {now:%Y-%m-%d}") # 输出: 日期: 2025-05-26 print(f"时间: {now:%H:%M:%S}") # 输出: 时间: 15:01:15 print(f"当地时间: {now:%c}") # 输出: 当地时间: Mon May 26 15:01:15 2025 print(f"12小时制: {now:%I%p}") # 输出: 12小时制: 03PM
进阶技巧
嵌套 f-string
value = 42 print(f"{f'The value is {value}':^30}") # 输出: ' The value is 42 '
动态格式化参数
width = 20 precision = 2 num = 3.14159 print(f"Pi: '{num:^{width}.{precision}f}'") # 输出: Pi: ' 3.14 '
表格对齐
print(f"{'ID':<5} {'Name':<10} {'Score':>6}") print(f"1 {'Alice'} {85.5:>6.2f}") print(f"2 {'Bob'} {92.0:>6.2f}") # 输出: # ID Name Score # 1 Alice 85.50 # 2 Bob 92.00
自记录表达式(调试输出)
f-string 支持在花括号内使用 = 符号来输出表达式及其结果,这在调试时非常有用:
a, b = 10, 5 print(f"{a = }") # 输出: a = 10 print(f"{a + b = }") # 输出: a + b = 15 print(f"{a * b = }") # 输出: a * b = 50 print(f"{bool(a) = }") # 输出: bool(a) = True
与其他格式化方法的对比
| 方法 | 优点 | 缺点 |
|---|---|---|
% 格式化 |
语法简单 | 可读性差,不支持复杂格式化 |
str.format() |
灵活性高 | 代码冗长 |
f-string |
简洁、高效、可读性强 | 需 Python 3.6+ |