刘心向学(52):f-string —— 字符串格式化的现代之道

内容分享2个月前发布
0 0 0

刘心向学(52):f-string —— 字符串格式化的现代之道

分享兴趣,传播快乐,增长见闻,留下美好!亲爱的您,这里是LearningYard新学苑。今天小编为大家带来文章“刘心向学(52):f-string —— 字符串格式化的现代之道”欢迎您的访问。Share interest, spread happiness,Increase knowledge, leave a beautiful!Dear, this is LearningYard Academy.Today, the editor brings you an article.”Liu Xin Xiang Xue (52): f-string — The Modern Way to Format Strings”Welcome to your visit.

一、思维导图(MindMap)

刘心向学(52):f-string —— 字符串格式化的现代之道

二、引言(Introduction)

你是否写过这样的代码?

Have you written code like this?

Python编辑name = "Alice"
age = 25
# 旧方式:繁琐且易错
print("Hello, " + name + ". You are " + str(age) + " years old.")
# 或使用 % 格式化
print("Hello, %s. You are %d years old." % (name, age))
# 或使用 str.format()
print("Hello, {}. You are {} years old.".format(name, age))

这些方式要么冗长,要么可读性差。

These approaches are either clunky or hard to read.

从 Python 3.6 起,推荐使用:

Since Python 3.6, there's a better way:

f-string

它让你在字符串中直接嵌入表达式,简洁、高效、直观。

It allows you to embed expressions directly inside strings — clean, fast, and intuitive.


三、基本语法(Basic Syntax)

Python编辑f"Hello, {name}. You are {age} years old."
  • 在字符串前加 f 或 F
  • Prefix the string with f or F
  • {}
  • 中可放入变量、表达式、函数调用等
  • can contain variables, expressions, function calls, etc.
  • 支持格式化(如 :.2f、!r 等)

Supports formatting (e.g., :.2f, !r)

示例

Example

Python编辑price = 19.985
tax = 0.13

f"Price: ${price:.2f}, Total: ${price * (1 + tax):.2f}"
# 输出: Price: $19.99, Total: $22.58

f"Name: {name.upper()!r}"# !r 表明 repr()
# 输出: Name: 'ALICE'

四、实战场景(Practical Use Cases)

1. 日志与调试

Logging and Debugging

Python编辑x, y = 1020
print(f"DEBUG: x={x}, y={y}, sum={x+y}")
# 输出: DEBUG: x=10, y=20, sum=30

2. 动态内容生成

Dynamic Content Generation

Python编辑users = ["Alice""Bob""Charlie"]
messages = [f"Hello, {user}!"for user in users]

3. 数值格式化

Number Formatting

Python编辑ratio = 0.756
f"Success rate: {ratio:.1%}"# 百分比
# 输出: Success rate: 75.6%

f"Hex: {255:x}, Binary: {255:b}"
# 输出: Hex: ff, Binary: 11111111

4. 多行 f-string

Multi-line f-strings

Python编辑info = f"""
Name: {name}
Age:  {age}
Year of Birth: {2025 - age}
"""

五、注意事项(Caveats)

  • f-string
  • 在定义时求值,不支持延迟渲染
  • 避免在循环中重复构建一样的 f-string(可提取变量)
  • 不要在 {} 中做复杂逻辑,影响可读性
  • 注意引号嵌套:f”Say: {'hello'}” 是合法的

六、结语(Conclusion)

f-string 是 Python 字符串格式化的现代标准

f-string is the modern standard for string formatting in Python.

它让代码更接近自然语言,提升可读性与开发效率。

It brings code closer to natural language, improving readability and developer efficiency.

从今天起,当你拼接字符串时,请问自己:

From now on, when you concatenate strings, ask yourself:

“我是不是该用 f-string?”

“Should I use an f-string?”

答案,几乎总是肯定的。

The answer is almost always yes.

由于真正的 Pythonic 代码,是让表达更贴近思维

Because truly Pythonic code expresses intent as naturally as thought.

而 f-string,正是这一理念的完美体现。

And f-string is the perfect embodiment of that principle.


今天的分享就到这里了。
如果您对文章有独特的想法,
欢迎给我们留言,
让我们相约明天。
祝您今天过得开心快乐!
That's all for today's sharing.
If you have a unique idea about the article,
please leave us a message,
and let us meet tomorrow.
I wish you a nice day!

参考资料:通义千问

参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.

Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.

本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通!

LearningYard新学苑

文字:song
排版:song
审核|qiu

© 版权声明

相关文章

暂无评论

none
暂无评论...