這段代碼做了什麼?這個Fancier輸出的解釋python的格式代碼
for x in range(1,11):
print('{0:2d} {1:3d} {2:4d}'.format(x,x**2,x**3))
這段代碼做了什麼?這個Fancier輸出的解釋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 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
功能括號變量的指數:
>>> 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
爲八進制等
閱讀docs [文檔](https://docs.python.org/3/library/ string.html#formatstrings)! – schwobaseggl