跳到主要内容

Python F-字符串

什么是F-字符串?

F-字符串(Format strings)是Python 3.6及以上版本引入的一种字符串格式化方法,正式名称为"格式化字符串字面值"(Formatted string literals)。F-字符串提供了一种简洁、直观的方式来在字符串中嵌入Python表达式。

通过在字符串前添加字母fF前缀,你可以在字符串内部的花括号{}中放置Python表达式,这些表达式会在运行时被计算并转换为字符串。

基本语法

F-字符串的基本语法如下:

python
f"字符串内容 {表达式} 更多字符串内容"

也可以使用单引号:

python
f'字符串内容 {表达式} 更多字符串内容'

F-字符串与其他格式化方法对比

Python中存在多种字符串格式化方法,让我们看看F-字符串与它们的对比:

python
name = "Alice"
age = 25

# 1. % 运算符 (旧式字符串格式化)
print("My name is %s and I am %d years old." % (name, age))

# 2. str.format() 方法
print("My name is {} and I am {} years old.".format(name, age))

# 3. F-字符串
print(f"My name is {name} and I am {age} years old.")

输出(三种方法结果相同):

My name is Alice and I am 25 years old.
提示

F-字符串通常被认为是最简洁、最直观的方法,同时执行效率也较高。

F-字符串的高级功能

1. 在花括号中使用表达式

F-字符串可以包含任何有效的Python表达式:

python
x = 10
y = 20
print(f"The sum of {x} and {y} is {x + y}")

输出:

The sum of 10 and 20 is 30

2. 调用函数

可以在F-字符串中调用函数:

python
def get_greeting(name):
return f"Hello, {name}!"

username = "Bob"
print(f"{get_greeting(username)}")

输出:

Hello, Bob!

3. 引用对象属性和方法

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

def get_info(self):
return f"{self.name} is {self.age} years old"

person = Person("Charlie", 30)
print(f"Person info: {person.get_info()}")
print(f"Name: {person.name}, Age: {person.age}")

输出:

Person info: Charlie is 30 years old
Name: Charlie, Age: 30

4. 格式化选项

F-字符串支持与str.format()相同的格式规范:

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

big_number = 1000000
print(f"Using comma as thousand separator: {big_number:,}")

percentage = 0.75
print(f"As percentage: {percentage:.2%}")

输出:

Pi rounded to 2 decimal places: 3.14
Using comma as thousand separator: 1,000,000
As percentage: 75.00%

5. 对齐和填充

python
for i in range(1, 11):
print(f"{i:2d} squared is {i*i:3d}")

输出:

 1 squared is   1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100

6. 转义花括号

如果需要在F-字符串中使用花括号字符,需要使用双花括号转义:

python
print(f"This is a literal curly brace: {{")
print(f"This is another literal curly brace: }}")

输出:

This is a literal curly brace: {
This is another literal curly brace: }

7. 多行F-字符串

python
name = "David"
age = 35
occupation = "Developer"

info = (
f"Name: {name}\n"
f"Age: {age}\n"
f"Occupation: {occupation}"
)

print(info)

输出:

Name: David
Age: 35
Occupation: Developer

Python 3.8+ 的调试表达式

从Python 3.8开始,F-字符串支持=说明符,它可以显示表达式文本及其结果,这在调试时非常有用:

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

输出:

x=10, y=20, x+y=30

实际应用场景

1. 数据格式化与报表生成

python
def generate_invoice(items, customer_name):
total = sum(price for item, price in items)
invoice = f"INVOICE\nCustomer: {customer_name}\n\n"
invoice += "Item".ljust(30) + "Price\n"
invoice += "-" * 40 + "\n"

for item, price in items:
invoice += f"{item}".ljust(30) + f"${price:.2f}\n"

invoice += "-" * 40 + "\n"
invoice += "Total:".ljust(30) + f"${total:.2f}"
return invoice

items = [("Laptop", 999.99), ("Mouse", 24.50), ("Keyboard", 59.95)]
print(generate_invoice(items, "John Doe"))

输出:

INVOICE
Customer: John Doe

Item Price
----------------------------------------
Laptop $999.99
Mouse $24.50
Keyboard $59.95
----------------------------------------
Total: $1084.44

2. 构建URL或文件路径

python
def build_api_url(base_url, endpoint, params=None):
url = f"{base_url.rstrip('/')}/{endpoint.lstrip('/')}"
if params:
query_string = "&".join([f"{key}={value}" for key, value in params.items()])
url = f"{url}?{query_string}"
return url

base = "https://api.example.com"
endpoint = "/users"
params = {"limit": 10, "offset": 20}

url = build_api_url(base, endpoint, params)
print(url)

输出:

https://api.example.com/users?limit=10&offset=20

3. 日志记录

python
import time

def log_action(action, user, status):
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"[{timestamp}] {action} by {user}: {status}"
print(log_entry) # 在实际应用中,这里会写入日志文件
return log_entry

log_action("Login", "user123", "Success")
log_action("Database update", "admin", "Failed")

输出(时间戳会根据当前时间变化):

[2023-10-25 14:30:45] Login by user123: Success
[2023-10-25 14:30:45] Database update by admin: Failed

最佳实践与注意事项

  1. 可读性优先:虽然可以在F-字符串中放置复杂表达式,但为了代码可读性,应避免过于复杂的表达式。

  2. 性能考虑:F-字符串通常比其他格式化方法更快,但仍然应注意在循环中构建大量字符串的性能影响。

  3. 版本兼容性:F-字符串需要Python 3.6+,如果需要兼容较老版本的Python,请使用其他格式化方法。

  4. 引号匹配:在F-字符串中使用引号时,需注意与字符串定界符的匹配:

python
# 正确
message = f"She said, \"Hello!\""
# 或者使用不同类型的引号
message = f'She said, "Hello!"'

总结

F-字符串是Python中一种强大而直观的字符串格式化工具,它具有以下优势:

  • 语法简洁明了
  • 可以直接引用变量和表达式
  • 支持丰富的格式化选项
  • 执行效率较高
  • 特别适合需要动态生成文本内容的场景

作为Python 3.6引入的相对较新特性,F-字符串已成为Python开发者处理字符串格式化的首选方法。通过掌握F-字符串,你可以编写更简洁、更易读的代码。

练习

  1. 使用F-字符串创建一个函数,接受姓名、年龄和职业,返回一个格式化的自我介绍。
  2. 创建一个小型表格,显示1到10的数字、它们的平方和立方,使用F-字符串确保对齐良好。
  3. 实现一个函数,接受一个产品列表(每个产品包含名称和价格),使用F-字符串生成一个格式化的购物清单,包括总价。

延伸阅读