该
f方法格式化字符串字面量 和它的新功能
Python 3.6。
甲 格式的字符串文字 或 F-串
是前缀字符串文字'f'或'F'。这些字符串可能包含替换字段,这些替换字段由花括号分隔{}。尽管其他字符串文字始终具有恒定值,但是格式化的字符串实际上是在运行时评估的表达式。
格式化字符串文字的一些示例:
>>> name = "Fred">>> f"He said his name is {name}.""He said his name is Fred.">>> name = "Fred">>> f"He said his name is {name!r}.""He said his name is Fred.">>> f"He said his name is {repr(name)}." # repr() is equivalent to !r"He said his name is Fred.">>> width = 10>>> precision = 4>>> value = decimal.Decimal("12.34567")>>> f"result: {value:{width}.{precision}}" # nested fieldsresult: 12.35>>> today = datetime(year=2017, month=1, day=27)>>> f"{today:%B %d, %Y}" # using date format specifierJanuary 27, 2017>>> number = 1024>>> f"{number:#0x}" # using integer format specifier0x400


