在 Python 的历史中,字符串格式化的发展源远流长。在 Python 2.6 之前,想要格式化一个字符串,只能使用 % 这个占位符,或者string.Template 模块。不久之后,出现了更灵活更靠谱的字符串格式化方式: str.format 方法。
过去使用 % 做字符串格式化方式的代码样例:
>>> msg = 'hello world'
>>> 'msg: %s' % msg
'msg: hello world'
用string.format的样例:
>>> msg = 'hello world'
>>> 'msg: {}'.format(msg)
'msg: hello world'
为了进一步简化格式化方法,Eric Smith 在2015年提交了 PEP 498 — Literal String Interpolation 提案。
PEP 498 提出了一种新的字符串插值方法,该方法可以更简单便捷的使用 str.format 方法。只需要在字符串开头加上一个字母 f,形成 f” “ 的格式就可以了。
使用f-string的样例:
>>> msg = 'hello world'
>>> f'msg: {msg}'
'msg: hello world'
这就可以了!再也不需要用 string.format 或者 % 了。不过 f-string 并不能完全替代 str.format。