格式化符号 | 說明 |
---|---|
%c | 轉換成字元(ASCII 碼值,或者長度為一的字元串) |
%r | 優先用repr()函數進行字元串轉換(Python2.0新增) |
%s | 優先用str()函數進行字元串轉換 |
%d / %i | 轉成有符号十進制數 |
%u | 轉成無符号十進制數 |
%o | 轉成無符号八進制數 |
%x / %X | (Unsigned)轉成無符号十六進制數(x / X 代表轉換後的十六進制字元的大 小寫) |
%e / %E | 轉成科學計數法(e / E控制輸出e / E) |
%f / %F | 轉成浮點數(小數部分自然截斷) |
%g / %G | %e和%f / %E和%F 的簡寫 |
%% | 輸出% |
>>> #列印字元串
>>> print('My name is %s' % 'Rusky')
My name is Rusky
>>> #列印整數
>>> print('He is %d years old' % (26))
He is 26 years old
>>> #列印浮點數
>>> print('His height is %f M' % (1.78))
His height is 1.780000 M
>>> print('His height is %.2f M' % (1.78))
His height is 1.78 M
>>> #指定占位符寬度
>>> print('Name:%10s Age:%8d Height:%8.2f' % ('Rusky',26,1.78))
Name: Rusky Age: 26 Height: 1.78
>>> #指定占位符寬度-左對齊
>>> print('Name:%-10s Age:%-8d Height:%-8.2f' % ('Rusky',26,1.78))
Name:Rusky Age:26 Height:1.78
>>> #科學計數法
>>> format(3.141592611111111111111,'.2e')
'3.14e+00'
>>>