話不多說 準備和%s 說再見吧!
一、str.format()
>>> "{} {}".format("hello", "world") # 不設置指定位置,按默認順序
'hello world'
>>> "{0} {1}".format("hello", "world") # 設置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 設置指定位置
'world hello world'
>>> "網站名:{name}, 地址 {url}".format(name="aaa", url="www.aaa.com")
'網站名:aaa, 地址 www.aaa.com'
>>> dict = {"name": "aaa", "url": "www.aaa.com"}
>>> # 通過字典設置參數
... "網站名:{name}, 地址 {url}".format(**dict)
'網站名:aaa, 地址 www.aaa.com'
>>> # 通過列表索引設置參數
...
>>> my_list = ['aaa', 'www.aaa.com']
>>> "網站名:{0[0]}, 地址 {0[1]}".format(my_list) # 0是必須的
'網站名:aaa, 地址 www.aaa.com'
>>> class Format_num(object):
... def __init__(self, value):
... self.value = value
...
>>> num = Format_num(1)
>>> 'value 爲: {0.value}'.format(num)
'value 爲: 1'
二、數字格式化
>>> print("{:.2f}".format(3.1415926));
3.14
數字 | 格式 | 輸出 | 描述 |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | 保留小數點後兩位 |
3.1415926 | {:+.2f} | +3.14 | 帶符號保留小數點後兩位 |
-1 | {:+.2f} | -1.00 | 帶符號保留小數點後兩位 |
2.71828 | {:.0f} | 3 | 不帶小數 |
5 | {:0>2d} | 05 | 數字補零 (填充左邊, 寬度爲2) |
5 | {:x<4d} | 5xxx | 數字補x (填充右邊, 寬度爲4) |
10 | {:x<4d} | 10xx | 數字補x (填充右邊, 寬度爲4) |
1000000 | {:,} | 1000000 | 以逗號分隔的數字格式 |
0.25 | {:.2%} | 25.00% | 百分比格式 |
1000000000 | {:.2e} | 1.00e+09 | 指數記法 |
13 | {:10d} | 13 | 右對齊 (默認, 寬度爲10) |
13 | {:<10d} | 13 | 左對齊 (寬度爲10) |
13 | {:^10d} | 13 | 中間對齊 (寬度爲10) |
'{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
1011
11
13
b
0xb
0XB
^, <, > 分別是居中、左對齊、右對齊,後面帶寬度, : 號後面帶填充的字符,只能是一個字符,不指定則默認是用空格填充。
+ 表示在正數前顯示 +,負數前顯示 -; (空格)表示在正數前加空格。
b、d、o、x 分別是二進制、十進制、八進制、十六進制。