Python中的f-string:更优雅的字符串格式化
在Python 3.6中引入的f-string(格式化字符串字面值)彻底改变了字符串格式化的方式。它不仅语法简洁,执行效率也比传统的%格式化和str.format()方法更高。
基本用法
name = "Alice"
age = 30
print(f"Hello, {name}. You are {age} years old.")
高级特性
f-string支持表达式和函数调用:
price = 19.99
quantity = 3
print(f"Total: {price * quantity:.2f}")
# 调用函数
def get_name():
return "Bob"
print(f"Name: {get_name()}")
格式规范
f-string提供了丰富的格式选项:
from datetime import datetime
now = datetime.now()
print(f"Current time: {now:%Y-%m-%d %H:%M:%S}")
number = 1234.5678
print(f"Formatted: {number:,.2f}") # 输出: 1,234.57
调试技巧
Python 3.8引入了自调试表达式:
value = 42
print(f"{value = }") # 输出: value = 42
f-string让字符串格式化变得直观易读,是现代Python开发中不可或缺的工具。掌握它的使用能显著提升代码的可读性和开发效率。