格式化的字符串文字以前缀'f'
为的格式字符串为前缀,并且与之接受的格式字符串类似str.format()
。它们包含由花括号包围的替换字段。替换字段是表达式,在运行时进行评估,然后使用format()
协议进行格式化 :
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
'result: 12.35'