Python f-string 格式化操作详解

Python 的 f-string(格式化字符串)自 3.6 版本引入,是一种高效且简洁的字符串格式化方式。它通过在字符串前加 fF 来启用,并允许直接在大括号 {} 中嵌入表达式或变量,大幅提高了代码的可读性和开发效率。


一、f-string 基础用法

1. 简单变量插值

name = "Alice"

age = 25

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

# 输出: My name is Alice, and I am 25 years old.

2. 表达式插值

f-string 支持在 {} 中嵌入任意的表达式:

a = 10

b = 20

print(f"The sum of {a} and {b} is {a + b}.")

# 输出: The sum of 10 and 20 is 30.

3. 调用函数

import math

radius = 5

print(f"The area of a circle with radius {radius} is {math.pi * radius ** 2:.2f}.")

# 输出: The area of a circle with radius 5 is 78.54.


二、格式化字符串的增强功能

1. 控制数字格式

f-string 支持丰富的格式控制符:

小数点控制

pi = 3.14159

print(f"Pi rounded to 2 decimal places: {pi:.2f}")

# 输出: Pi rounded to 2 decimal places: 3.14

数字宽度与填充

num = 42

print(f"Number with leading zeros: {num:05}")

# 输出: Number with leading zeros: 00042

千位分隔符

large_number = 1234567890

print(f"Formatted number: {large_number:,}")

# 输出: Formatted number: 1,234,567,890

2. 对齐方式

name = "Alice"

print(f"Left aligned: '{name:<10}'")

print(f"Right aligned: '{name:>10}'")

print(f"Center aligned: '{name:^10}'")

# 输出:

# Left aligned: 'Alice '

# Right aligned: ' Alice'

# Center aligned: ' Alice '


三、高级用法

1. 嵌套 f-string

在某些场景下,可能需要嵌套 f-string:

value = 42

formatted = f"{f'The value is {value}':^30}"

print(formatted) # 输出: The value is 42

2. 使用字典或对象

f-string 可以直接插值字典键值或对象属性:

person = {"name": "Alice", "age": 25}
print(f"Name: {person['name']}, Age: {person['age']}")
# 输出: Name: Alice, Age: 25

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Bob", 30)
print(f"Name: {p.name}, Age: {p.age}")
# 输出: Name: Bob, Age: 30
3. 使用 = 输出调试信息

Python 3.8 引入了 f-string 的调试功能,可以使用 = 来显示表达式和结果:

a = 5
b = 10
print(f"{a=}, {b=}, {a + b=}")
# 输出: a=5, b=10, a + b=15
4. 结合多行字符串
name = "Alice"
age = 25
info = (
    f"Name: {name}\n"
    f"Age: {age}\n"
    f"Is adult: {age >= 18}"
)
print(info)
# 输出:
# Name: Alice
# Age: 25
# Is adult: True

五、f-string 的注意事项

  1. 仅支持 Python 3.6 及以上版本
    如果使用旧版本 Python,请考虑使用 str.format()%

  2. 不能包含反斜杠 \
    在 f-string 中不能直接使用反斜杠,若需要换行,使用多行字符串。

  3. 性能优越
    f-string 是目前最快的字符串格式化方式,优于 str.format()%


六、性能对比

import timeit

name = "Alice"
age = 25

# f-string
f_string_time = timeit.timeit(lambda: f"My name is {name}, and I am {age} years old.", number=1000000)

# str.format
str_format_time = timeit.timeit(lambda: "My name is {}, and I am {} years old.".format(name, age), number=1000000)

# %
percent_time = timeit.timeit(lambda: "My name is %s, and I am %d years old." % (name, age), number=1000000)

print(f"f-string: {f_string_time:.2f}s, str.format: {str_format_time:.2f}s, %: {percent_time:.2f}s")
# 示例输出: f-string: 0.12s, str.format: 0.18s, %: 0.16s

七、总结

f-string 是 Python 中功能强大、语法简洁、性能优越的字符串格式化工具。它不仅支持变量插值,还可以进行表达式计算、格式化控制、调试输出等操作,非常适合现代 Python 开发。通过掌握 f-string 的各种用法,你可以更高效地处理字符串相关的任务。

作者:威桑

物联沃分享整理
物联沃-IOTWORD物联网 » Python f-string 格式化操作详解

发表回复