解释python的输出格式化代码
这个代码是做什么的解释python的输出格式化代码,python,output,Python,Output,这个代码是做什么的 for x in range(1,11): print('{0:2d} {1:3d} {2:4d}'.format(x,x**2,x**3)) 下面是一个例子: s = "{2:2d}\n{0:3d}\n{1:4d}".format(2, 4, 6) print(s) --output:-- 6 2 4 让我们简化一下: 我们需要打印三个变量: >>> x = 1 >>> y = 2 >>> z
for x in range(1,11):
print('{0:2d} {1:3d} {2:4d}'.format(x,x**2,x**3))
下面是一个例子:
s = "{2:2d}\n{0:3d}\n{1:4d}".format(2, 4, 6)
print(s)
--output:--
6
2
4
让我们简化一下:
我们需要打印三个变量:
>>> x = 1
>>> y = 2
>>> z = 3
我们可以使用format方法获得清晰的输出:
每个大括号中的第一个数字(在:
字符之前)是格式
函数括号中变量的索引:
>>> print('{0:2d} {1:3d} {2:4d}'.format(x,y,z))
1 2 3
>>> print('{2:2d} {1:3d} {0:4d}'.format(x,y,z))
3 2 1
大括号中的第二个数字(字符:
后的数字)是要在其中显示值的字段的最小宽度。默认情况下右对齐:
>>> print('{2:2d} {1:3d} {0:4d}'.format(x,y,z))
3 2 1
>>> print('{2:5d} {1:5d} {0:5d}'.format(x,y,z))
3 2 1
>>> print('{2:10d} {1:10d} {0:10d}'.format(x,y,z))
3 2 1
>>>
和d
平均十进制整数。输出以10为基数的数字:
>>> print('{2:1f} {1:10f} {0:10d}'.format(x,y,z))
3.000000 2.000000 1
>>> print('{2:1d} {1:10d} {0:10f}'.format(x,y,z))
3 2 1.000000
>>>
f
表示浮点数,o
表示八进制等。阅读文档!大括号中的第二个数字(字符后面的数字)代表我们希望在打印下一个变量之前使用的空格——Nope。print“{0:2}{1:2}{2:2}”。format(10,20,30)
的输出是102030
@7stud您又对了。非常感谢。我从你的回答中借用了一大堆句子:)
>>> print('{2:1f} {1:10f} {0:10d}'.format(x,y,z))
3.000000 2.000000 1
>>> print('{2:1d} {1:10d} {0:10f}'.format(x,y,z))
3 2 1.000000
>>>