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 '
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
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':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+ |
参与评论
手机查看
返回顶部