2016-04-24 27 views

回答

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

讓我們把它簡單:

我們有我們想要打印出來三個變量:

>>> 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爲八進制等

+0

*大括號中的第二個數字(後面的數字:字符)代表打印下一個變量之前我們想要的空格* - 不是。 'print「{0:2} {1:2} {2:2}」格式(10,20,30)'的輸出是'102030'。 – 7stud

+0

@ 7stud你又合適了。謝謝。我從你的回答中借了一堆句子:) – EbraHim