Python字符串格式化利器:f-strings入门指南
在Python中,字符串格式化经历了多次演进:从传统的%
占位符到str.format()
,再到Python 3.6引入的f-strings(格式化字符串字面值)。它凭借简洁的语法和强大的功能,已成为现代Python开发的首选方案。
✨ 基础用法
直接在字符串前加f
前缀,变量用{}
包裹:
name = "Alice"
age = 30
print(f"Hello, {name}! You are {age} years old.")
# 输出: Hello, Alice! You are 30 years old.
⚡️ 执行表达式
{}
内可直接运行表达式或调用函数:
print(f"10 + 20 = {10 + 20}") # 输出: 10 + 20 = 30
print(f"Name uppercase: {name.upper()}") # 输出: Name uppercase: ALICE
🔢 数字格式化
轻松控制浮点数精度和格式:
price = 49.99
print(f"Price: {price:.2f} USD") # 输出: Price: 49.99 USD
print(f"Hex: {255:#x}") # 输出: Hex: 0xff
📝 多行字符串
与三重引号结合使用:
user = {
"name": "Bob", "score": 85}
msg = f"""
User Report:
Name: {user['name']}
Score: {user['score']}/100
"""
print(msg)
💡 为什么选择f-strings?
- 简洁性:代码量比
%
和.format()
减少约50% - 可读性:变量名直接嵌入,逻辑一目了然
- 高性能:运行时效率比传统方式高2-3倍
根据Python官方建议:f-strings是大多数场景的最佳选择(PEP 498)。
掌握f-strings能让你的代码更简洁高效。尝试在下一个项目中替换旧的格式化方法,体验现代Python的优雅!