f-string

2019-06-23  本文已影响0人  粟米一粒

f-string

python3.6 引入了一种新的字符串常量:f-tring或者叫格式化字符串

f-string使用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'

性能

下图是各种字符串格式化方法的执行时间

image

参考

https://cito.github.io/blog/f-strings/

https://docs.python.org/3/whatsnew/3.6.html

上一篇下一篇

猜你喜欢

热点阅读