Featured image of post Python小技巧 - f-strings格式化字符串

Python小技巧 - f-strings格式化字符串

Python 3.8 中 f-strings 添加了一个"=",让f-strings使用起来更加方便

比如下面的代码

1
2
3
4
5
6

from datetime import date

user = 'durban'
member_since = date(1988, 1, 2)
print(f'{user=} {member_since=}')

运行后输出结果如下

1
2

user='durban' member_since=datetime.date(1988, 1, 2)

再比如下面的代码实例

1
2
3
4
5
6
7
8
9

from datetime import date

user = 'durban'
member_since = date(1988, 1, 2)

delta = date.today() - member_since

print(f'{user=!s} {delta.days=:,d}')

运行后输出结果如下

1
2

user=durban delta.days=11,937

再比如下面的代码实例

1
2
3
4
5

from math import cos, radians

theta = 45
print(f'{theta=} {cos(radians(theta))=:.3f}')

运行后结果如下

1
theta=45 cos(radians(theta))=0.707
Licensed under CC BY-NC-SA 4.0
最后更新于 Jul 30, 2025 11:03 +0800