Python格式化輸出之format

format用法

相對基本格式化輸出採用‘%’的方法,format()功能更強大,該函數把字符串當成一個模板,通過傳入的參數進行格式化,並且使用大括號‘{}’作爲特殊字符代替‘%’

使用方法由兩種:b.format(a)和format(a,b)

1、基本用法

(1)不帶編號,即“{}”

(2)帶數字編號,可調換順序,即“{1}”、“{2}”

(3)帶關鍵字,即“{a}”、“{tom}”

>>> print('{} {}'.format('hello','world'))  # 不帶字段
hello world
>>> print('{0} {1}'.format('hello','world'))  # 帶數字編號
hello world
>>> print('{0} {1} {0}'.format('hello','world'))  # 打亂順序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world'))  # 帶關鍵字
world hello world

2、進階用法

(1)< (默認)左對齊、> 右對齊、^ 中間對齊、= (只用於數字)在小數點後進行補齊

(2)取位數“{:4s}”、"{:.2f}"等

>>> print('{} and {}'.format('hello','world'))  # 默認左對齊
hello and world
>>> print('{:10s} and {:>10s}'.format('hello','world'))  # 取10位左對齊,取10位右對齊
hello      and      world
>>> print('{:^10s} and {:^10s}'.format('hello','world'))  # 取10位中間對齊
  hello    and   world   
>>> print('{} is {:.2f}'.format(1.123,1.123))  # 取2位小數
1.123 is 1.12
>>> print('{0} is {0:>10.2f}'.format(1.123))  # 取2位小數,右對齊,取10位
1.123 is       1.12

3、多種格式化

‘b’ - 二進制。將數字以2爲基數進行輸出。
‘c’ - 字符。在打印之前將整數轉換成對應的Unicode字符串。
‘d’ - 十進制整數。將數字以10爲基數進行輸出。
‘o’ - 八進制。將數字以8爲基數進行輸出。
‘x’ - 十六進制。將數字以16爲基數進行輸出,9以上的位數用小寫字母。
‘e’ - 冪符號。用科學計數法打印數字。用’e’表示冪。
‘g’ - 一般格式。將數值以fixed-point格式輸出。當數值特別大的時候,用冪形式打印。
‘n’ - 數字。當值爲整數時和’d’相同,值爲浮點數時和’g’相同。不同的是它會根據區域設置插入數字分隔符。
‘%’ - 百分數。將數值乘以100然後以fixed-point(‘f’)格式打印,值後面會有一個百分號。

>>> print('{0:b}'.format(3))
11
>>> print('{:c}'.format(20))

>>> print('{:d}'.format(20))
20
>>> print('{:o}'.format(20))
24
>>> print('{:x}'.format(20))
14
>>> print('{:e}'.format(20))
2.000000e+01
>>> print('{:g}'.format(20.1))
20.1
>>> print('{:f}'.format(20))
20.000000
>>> print('{:n}'.format(20))
20
>>> print('{:%}'.format(20))
2000.000000%
>>> 

>>> print('{0:b}'.format(3))
>>> print('{:c}'.format(20))

>>> print('{:d}'.format(20))
>>> print('{:o}'.format(20))
>>> print('{:x}'.format(20))
>>> print('{:e}'.format(20))
2.000000e+01
>>> print('{:g}'.format(20.1))
20.1
>>> print('{:f}'.format(20))
20.000000
>>> print('{:n}'.format(20))
>>> print('{:%}'.format(20))
2000.000000%
>>>


通過位置匹配參數


>>>
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+版本支持
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')  # 可打亂順序
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')  # 可重複
'abracadabra'


通過名字匹配參數

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

通過屬性匹配參數


>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
...  'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __str__(self):
...         return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'


通過下標或key匹配參數


>>>
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'
>>> a = {'a': 'test_a', 'b': 'test_b'}
>>> 'X: {0[a]};  Y: {0[b]}'.format(a)
'X: test_a;  Y: test_b'


佔位符%s和%r
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
conversion ::= "r" | "s" | "a"
這裏只有三個轉換符號,用"!"開頭。
"!r"對應 repr()"!s"對應 str(); "!a"對應ascii()>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"  # 輸出結果是一個帶引號,一個不帶

設置長度及對齊


>>> '{:<30}'.format('left aligned')  # 左對齊
'left aligned                  '
>>> '{:>30}'.format('right aligned')  # 右對齊
'                 right aligned'
>>> '{:^30}'.format('centered')  # 中間對齊
'           centered           '
>>> '{:*^30}'.format('centered')  # 使用“*”填充
'***********centered***********'
>>>'{:0=30}'.format(11)  # 還有“=”只能應用於數字,這種方法可用“>”代替
'000000000000000000000000000011'


%+f, %-f,% f的用法


>>>
>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # 總是顯示符號
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14)  # 若是+數,則在前面留空格
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # -數時顯示-,與'{:f}; {:f}'一致
'3.140000; -3.140000'2進制、10進制、16進制顯示


>>>
>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)  # 在前面加“#”,則帶進制前綴
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'


用“,”分隔數字,每一千進位

>>>
>>> '{:,}'.format(1234567890)
'1,234,567,890'

百分數%

>>>
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'

時間

>>>
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

佔位符嵌套


>>>
>>> for align, text in zip('<^>', ['left', 'center', 'right']):
...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'
>>> int(_, 16)  # 官方文檔給出來的,無法在IDLE復現
>>>
>>> width = 5
>>> for num in range(5,12):
...     for base in 'dXob':
...         print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
...     print()
...
    5     5   101
    6     6   110
    7     7   111
    8    10  1000
    9    11  1001
    A    12  1010
    B    13  1011
 
另,可在字符串前加f以達到格式化的目的,在{}里加入對象,此爲format的另一種形式:

name = 'jack'
age = 18
sex = 'man'
job = "IT"
salary = 9999.99

print(f'my name is {name.capitalize()}.')
print(f'I am {age:*^10} years old.')
print(f'I am a {sex}')
print(f'My salary is {salary:10.3f}')

# 結果
my name is Jack.
I am ****18**** years old.
I am a man
My salary is   9999.990
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章