当前位置:  首页>> 技术小册>> Python合辑5-格式化字符串

调试是f-string最常见的用途之一了。Python3.8 之前,很多人会用一种非常繁杂的hello = 42; f”hello = {hello}”来进行调试。针对此Python3.8引入了一个新功能。可以用 f”{hello=}” 重写上面的代码,而python会显示hello=42。下面这个例子展示了在使用函数表达式时如何应用该特性,其原理与上文代码是一样的。

  1. >>> def magic_number(): ...: return 42 ...:
  2. >>> f"{magic_number() = }"'magic_number() = 42'

该分类下的相关小册推荐: