在 Python 的众多字符串格式化方法中,格式化字符串字面量(Formatted String Literals,简称 f-string)是一种现代且高效的解决方案。

一、基本用法及特点

f-string 的语法形式为:

在字符串前添加前缀 f 或 F,并在字符串内部使用花括号 { } 插入变量或表达式。

name = "mediaTEA"
age = 7
print(f"My name is {name} and I am {age} years old.")

# 输出:My name is mediaTEA and I am 7 years old.

1、可在 { } 中插入任意有效的 Python 表达式。

print(f"The result of 5 + 3 is {5 + 3}")

# 输出:The result of 5 + 3 is 8

(1)自动将表达式结果转换为字符串类型,无需显式调用 str()。

(2)表达式求值在字符串生成时即时进行。

2、f-string 也可以用于调用函数,即插入函数调用表达式。

def square(x):
    return x * x

print(f"The square of 4 is {square(4)}")

# 输出:The square of 4 is 16

二、数字和日期的格式化

1、数值格式化

f-string 支持与 str.format() 类似的格式规范,可用于控制小数位数、对齐方式、宽度、千位分隔符等。

pi = 3.1415926
print(f"Pi rounded to 2 decimals: {pi:.2f}")

# 输出
# Pi rounded to 2 decimals: 3.14

常见格式:

{x:.2f} 保留两位小数 3.14

{x:10.2f} 占 10 个字符宽度,右对齐 ' 3.14'

{x:<10.2f} 左对齐 '3.14 '

{x:,.2f} 加千位分隔符 1,234.57

示例:

num = 1234.5678
print(f"Formatted: {num:,.2f}")

# 输出:Formatted: 1,234.57

2、日期格式化

使用 f-string 时,可直接在 { } 内使用日期格式控制符。

from datetime import datetime

now = datetime.now()
print(f"Current time: {now:%Y-%m-%d %H:%M:%S}")
# 输出:Current time: 2025-07-19 10:28:36

格式符与 strftime() 方法一致,可自由组合年、月、日、时、分、秒等组件。

三、使用字典和列表中的值

f-string 可直接在 { } 中嵌入对字典或列表元素的访问表达式,语法与常规表达式完全一致。

1、访问字典元素

person = {"name": "mediaTEA", "age": 7}
print(f"{person['name']} is {person['age']} years old.")

# 输出:mediaTEA is 7 years old.

2、访问列表元素

colors = ["red", "green", "blue"]
print(f"The first color is {colors[0]}.")

# 输出:The first color is red.

四、进阶用法

1、多行 f-string

多个 f-string 可通过括号组合,适用于构建多行结构化内容。

name = "mediaTEA"
score = 95

message = (
    f"Student: {name}\n"
    f"Score: {score}\n"
    f"Status: {'Pass' if score >= 60 else 'Fail'}"
)
print(message)

# 输出:
# Student: mediaTEA
# Score: 95
# Status: Pass

2、嵌套 f-string

f-string 可嵌套在表达式中使用,但应注意代码可读性。

value = 42
print(f"{f'Value is {value}'}!")

# 输出:Value is 42!

虽然可以嵌套 f-string,但建议在外层处理逻辑,避免混淆。

3、调试式 f-string

自 Python 3.8 起,f-string 支持调试风格写法(使用 = 号),支持快速输出变量及表达式值。

x = 10
y = 5
print(f"{x=}, {y=}, {x + y=}")

# 输出:x=10, y=5, x + y=15

◆ ◆

补充说明

1、版本限制

f-string 仅支持 Python 3.6 及以上版本,在早期版本中不可用。

2、推荐优先使用

相较 % 和 .format() 方法,f-string 更直观、可读性更高,性能也更优。

3、语法限制

{ } 内只能包含单行有效表达式,不允许包含赋值语句、控制结构或换行。

4、转义花括号

若要在字符串中输出花括号字符 { 或 },请使用双括号进行转义。

print(f"Use {{ and }} to represent curly braces.")

# 输出:Use { and } to represent curly braces.

点赞有美意,赞赏是鼓励