我正在将 Python 2 代码转换为 Python 3。目前我在将以下代码转换为 Python 3 时遇到困难。请帮忙。
print 'Data cache hit ratio: %4.2f%%' % ratio
另外,%4.2f%% 是什么意思?
尝试用format()重写代码。
只需在参数两边加上括号即可。
print('Data cache hit ratio: %4.2f%%' % ratio)
在 Python 3 中有更奇特的格式化方法,但这会起作用。
%4.2f
表示“在 4 个字符的字段中显示此浮点数,并带有小数点和后两位。因此,如“9.99”。%%
表示“显示百分号”。此处的格式直接来自C printf 函数。
f 表示定点符号。 %(4.2)前面的值分别表示数字的宽度(4)和精度(2)。
您可以使用 .format 或 f 字符串
print("Floating point {0:4.2f}".format(ratio))
print(f' Floating point {ratio:4.2f}')
这里 4 是正在打印的字段的总宽度,左边用空格填充。 2 是小数点后的位数。您可以在这里阅读更多相关信息https://docs.python.org/3/library/string.html#format-specification-mini-language
欢迎来到Python 3!
在 Python 3 中,
print
已被 print()
函数替换,并且字符串格式化运算符 %
通常被 .format()
方法或 f-strings 替换,以提高可读性。
以下是如何使用
f-strings
转换代码(在 Python 3.6 及更高版本中引入):
使用 f 字符串的 Python 3 版本:
print(f'Data cache hit ratio: {ratio:4.2f}%')
或者,如果您使用的是较旧的 Python 3 版本,则可以使用
.format()
方法:
使用 .format() 的 Python 3 版本:
print('Data cache hit ratio: {:4.2f}%'.format(ratio))
两种方法都会将比率格式化为小数点后两位,最小宽度为 4 个字符。