自动将旧字符串格式样式转换为 f 字符串

Automatically convert old string formatting style into f-strings

如何转换 Python 的旧格式字符串,如下所示:

print("You: %s points. Me: %s points." % (score, total - score))

进入以下?

print(f"You: {score} points. Me: {total - score} points.")

其实对于两个%s的情况,我写了这个正则表达式:

人们可以轻松地编写其他几个正则表达式来处理 1、3、4 ……%s 的情况,但我正在寻找一种更通用且更容易出错的方法。

注意:据我所知,2013 年有人在这里提出了类似的问题 (Automatic conversion of the advanced string formatter from the old style), when the f-strings were not a thing (they were introduced in Python 3.6)。

使用pyupgrade。具体来说,要启用转换为 f 字符串,请使用

pyupgrade --py36-plus <filename>

您可以使用

安装它
pip install pyupgrade

使用flynt。您使用目录名称调用它,它会递归搜索所有 .py 文件并将 % 格式转换为 f-strings。

flynt <directory_to_process>

它将转换 .format() 调用以及 % 格式。

您可以使用

安装它
pip install flynt

请注意,将 % 转换为 f 字符串并不完美,如果将单个元素元组传递给它们,将会产生不同的结果(这就是为什么 Python 从 %格式化)。