f-string 在 Python 中有多种特殊用法:

  • 插入表达式、调用函数、格式化数字和日期f-string 让我们可以直接在字符串中进行计算和格式化。
  • 多行字符串、条件格式化:非常适用于格式化多行文本或者根据条件动态改变输出内容。
  • 嵌套表达式、字典访问、调用方法:使得 f-string 可以处理更复杂的字符串插值。
  • 调试时输出变量名和值:通过 = 语法,方便调试时查看变量的值。

下面整理一下部分f-string的用法与示例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
print(f'{big_number:,}')    # 解释器会自动加上千分位标识符,输出 10,000,000,000,000,000
print(f"The number is {x:05d}.") # 输出: The number is 00042.

name: str = 'Jack'
age: int = 29
print(f'{name=}') # name='Jack'
print(f'{age=}') # age=29
print(f'{5+10=}') # 5+10=15


x = 5
y = 10
print(f"The sum of {x} and {y} is {x + y}.") # 直接插入表达式
# 输出: The sum of 5 and 10 is 15.

print(f"The result of ({x} + {y}) * 2 is {(x + y) * 2}.")
# 输出: The result of (5 + 10) * 2 is 30.


def multiply(a, b):
return a * b

print(f"The result of multiplying 3 and 4 is {multiply(3, 4)}.") # 调用函数
# 输出: The result of multiplying 3 and 4 is 12.


age = 25
print(f"You are {'young' if age < 30 else 'old'}.") # 使用条件表达式(三元运算符)
# 输出: You are young.


from datetime import datetime
today = datetime.today()

# 格式化日期
print(f"Today's date is {today:%Y-%m-%d}.")
# 输出: Today's date is 2024-12-18.

# 显示时间和日期
print(f"The current time is {today:%H:%M:%S}.")
# 输出: The current time is 14:30:15.


data = {"name": "Alice", "age": 30}
print(f"Name: {data['name']:s}, Age: {data['age']:d}.") # 字典格式化