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:,}') print(f"The number is {x:05d}.")
name: str = 'Jack' age: int = 29 print(f'{name=}') print(f'{age=}') print(f'{5+10=}')
x = 5 y = 10 print(f"The sum of {x} and {y} is {x + y}.")
print(f"The result of ({x} + {y}) * 2 is {(x + y) * 2}.")
def multiply(a, b): return a * b
print(f"The result of multiplying 3 and 4 is {multiply(3, 4)}.")
age = 25 print(f"You are {'young' if age < 30 else 'old'}.")
from datetime import datetime today = datetime.today()
print(f"Today's date is {today:%Y-%m-%d}.")
print(f"The current time is {today:%H:%M:%S}.")
data = {"name": "Alice", "age": 30} print(f"Name: {data['name']:s}, Age: {data['age']:d}.")
|