这段代码有什么作用?
for x in range(1,11):
print('{0:2d} {1:3d} {2:4d}'.format(x,x**2,x**3))
答案 0 :(得分: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 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
答案 1 :(得分:1)
让我们更简单:
我们要打印三个变量:
>>> 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
用于八进制等等。