Python 有几种方式来构建包含动态值的字符串。现代推荐的方法是 f-string(格式化字符串字面量),在 Python 3.6 中引入。
f-strings — 现代默认方式
python
name = "Ann"
age = 30
msg = f"{name} is {age} years old"
f 前缀让你直接在 {} 中嵌入表达式 — 简洁、易读且高效。这是现代 Python 中的首选方法。
f"{3.14159:.2f}" # "3.14" — 2 decimal places
f"{1000000:,}" # "1,000,000" — thousands separator
f"{0.85:.1%}" # "85.0%" — percentage
f"{42:05d}" # "00042" — pad with zeros to width 5
f"{'hi':>10}" # " hi" — right-align in width 10
f"{'hi':^10}" # " hi " — center
值后面的 :spec 控制精度、填充、对齐和数字格式化 — 强大的工具,可用于生成整洁的输出。
f"{name=}" # "name='Ann'" — prints both the expression AND value
= 对快速调试很便利 — 它会显示变量名和它的值。
"{} is {}".format(name, age) # str.format() — pre-f-string standard
"%s is %d" % (name, age) # %-formatting — old C-style (avoid in new code)
name + " is " + str(age) # concatenation — verbose, error-prone
.format() 在旧代码中仍然常见;%-格式化是遗留方法;原始拼接不被推荐(冗长且需要手动 str() 转换)。
字符串格式化需要频繁使用 — 构建消息、日志、输出、查询。
f-strings 是现代、易读且高效的标准,掌握它们的格式说明符(精度、填充、对齐、分隔符)让你能够生成整洁、专业的输出,而无需冗长的代码。
认识旧的 .format() 和 % 风格有助于阅读现有代码库。
熟练使用 f-strings 是编写清晰、符合 Python 习惯的代码的一个小而重要的部分。