[英]Explaination of this Fancier Output Formatting code of python
这段代码有什么作用?
for x in range(1,11):
print('{0:2d} {1:3d} {2:4d}'.format(x,x**2,x**3))
0: | 1: | 2: => The position in the arg list from which to get
the value. The order can be anything you want, and
you can repeat values, e.g. '{2:...} {0:...} {1:...} {0:...}'
2 | 3 | 4 => The minimum width of the field in which to display
the value. Right justified by default for numbers.
d => The value must be an integer and it will be displayed in
base 10 format (v. hex, octal, or binary format)
下面是一个例子:
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 方法来获得干净的输出:
每个大括号中的第一个数字(在:
字符之前)是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
表示八进制数等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.