python字符串格式化f-string

以前的方法

>>> name = 'Runoob'
>>> 'Hello %s' % name
'Hello Runoob'

python3.6 之后版本

f-string 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去
>>> name = 'Runoob'
>>> f'Hello {name}'  # 替换变量

>>> f'{1+2}'         # 使用表达式
'3'

>>> w = {'name': 'Runoob', 'url': 'www.runoob.com'}
>>> f'{w["name"]}: {w["url"]}'
'Runoob: www.runoob.com'

用了这种方式明显更简单了,不用再去判断使用 %s,还是 %d。

Python 3.8 的版本中可以使用 = 符号来拼接运算表达式与结果:
>>> x = 1
>>> print(f'{x+1}')   # Python 3.6
2

>>> x = 1
>>> print(f'{x+1=}')   # Python 3.8
'x+1=2

原文地址:https://www.cnblogs.com/lazy-sang/p/12761759.html