Python 2转Python 3:print语句转换求助及格式符含义解析
Python 2 转 Python 3:print语句转换与格式说明解析
原代码的Python 3适配
原Python 2代码:
print 'Data cache hit ratio: %4.2f%%' % ratio
转换为Python 3只需给print加上括号(Python 3中print是内置函数),格式化语法可直接沿用:
print('Data cache hit ratio: %4.2f%%' % ratio)
格式符%4.2f%%的含义
拆解来看:
%4.2f:浮点数格式化规则f:指定输出为浮点数类型.2:强制保留小数点后2位4:设置输出数字的最小宽度为4(包含小数点和小数部分),若数字实际长度小于4,会在前面补空格;若超过4则按实际长度输出
%%:转义输出单个%符号,因为单个%是格式化占位符的标识,需要用两个%才能输出真实的百分号
使用format()重写的方案
基础format写法
print('Data cache hit ratio: {:4.2f}%'.format(ratio))
若需明确指定参数位置,可写成:
print('Data cache hit ratio: {0:4.2f}%'.format(ratio))
更简洁的f-string写法(Python 3.6+推荐)
f-string是Python 3.6引入的格式化语法,可读性更高:
print(f'Data cache hit ratio: {ratio:4.2f}%')
内容的提问来源于stack exchange,提问作者Nijesh Nalan
相关产品推荐
相关产品推荐

