F-字符串
一句话解释
f-字符串 是 字符串 prefixed 使用 f 那个 embeds 表达式 in curly braces for inline 格式化.
用大白话说
f-字符串 (格式化字符串 literal) 是字符串 prefixed 使用 f or F 那个 lets 你 embed Python 表达式 directly 内部字符串 using curly braces {}.
F-strings were introduced in Python 3.6 and are the recommended way to format strings. They are faster and more readable than % 格式化 or .格式().
You can put any expression inside the braces: variables, arithmetic, function calls, even attribute access. Format specifiers go after a colon: f"{pi:.2f}" formats pi to 2 decimal places. Debugging is easier with f"{x=}" (Python 3.8+) which prints the variable name and value.
示例
name = "Alice"
age = 30
pi = 3.14159
# Basic f-string
print(f"Hello, {name}!") # Hello, Alice!
# Expressions inside braces
print(f"{name} is {age} years old") # Alice is 30 years old
print(f"Next year: {age + 1}") # Next year: 31
# Format specifiers
print(f"Pi: {pi:.2f}") # Pi: 3.14
print(f"Age: {age:>5}") # Age: 30
# Debug format (Python 3.8+)
print(f"{age=}") # age=30F-字符串 embed 表达式 in {} for inline 格式化. 它们 support 格式 specifiers 之后 colon.
常见混淆
容易混淆的对象: 格式 方法
关键区别: f-字符串 (f'...') embed 表达式 directly in 字符串. .格式() uses placeholders: '{}'.格式(值). f-字符串 是 faster, 更多 readable, and modern recommendation. Use f-字符串 for 新 code.
相关术语
相关资源
相关课程
- 字符串
F-字符串 格式化.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。