← 中文资源

简体中文版本

f-string 的 = 调试规格与转换符

f-string 的 = 规格把表达式原文和 repr 一起打印,自文档化调试零维护成本;!r/!s/!a 决定格式化前的形态,还能与 :.2f 这类格式规格组合使用。

阅读英文原文

实现说明

顶层就这几处状态:ratio、name、count。

使用要点

  • 每一步打印都带着自己的标签:repr:。

常见问题

安装包是准备工作的一部分吗?

不需要。只用内建 API,安装这一步可以省掉。 文件的状态由几个模块级绑定持有:ratio、name、count。

代码示例

ratio = 0.85
name = "café"
count = 3

# {expr=} is self-documenting debugging: expression text, equals sign, and repr in one print
print(f"{ratio=}")
print(f"{count * 2=}")
print(f"{list(range(3))=}")

# the !r/!s/!a conversions choose the pre-formatting shape: repr keeps quotes, ascii escapes non-ASCII
print(f"repr: {name!r} | str: {name!s} | ascii: {name!a}")

# the = specifier composes with format specs: equals sign first, precision after
print(f"{ratio=:.2f}")
print(f"{count=:03d}")