Python format 格式化函數

Python 字串 Python 字串


Python2.6 開始,新增了一種格式化字串的函數 str.format(),它增強了字串格式化的功能。

基本語法是通過 {}: 來代替以前的 %

format 函數可以接受不限個參數,位置可以不按順序。

實例

>>>"{} {}".format("hello", "world") # 不設置指定位置,按默認順序 'hello world' >>> "{0} {1}".format("hello", "world") # 設置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 設置指定位置 'world hello world'

也可以設置參數:

實例

#!/usr/bin/python # -*- coding: UTF-8 -*- print("網站名:{name}, 地址 {url}".format(name="IT研修", url="www.xuhuhu.com")) # 通過字典設置參數 site = {"name": "IT研修", "url": "www.xuhuhu.com"} print("網站名:{name}, 地址 {url}".format(**site)) # 通過列表索引設置參數 my_list = ['IT研修', 'www.xuhuhu.com'] print("網站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必須的

輸出結果為:

網站名:IT研修, 地址 www.xuhuhu.com
網站名:IT研修, 地址 www.xuhuhu.com
網站名:IT研修, 地址 www.xuhuhu.com

也可以向 str.format() 傳入對象:

實例

#!/usr/bin/python # -*- coding: UTF-8 -*- class AssignValue(object): def __init__(self, value): self.value = value my_value = AssignValue(6) print('value 為: {0.value}'.format(my_value)) # "0" 是可選的

輸出結果為:

value 為: 6

數字格式化

下表展示了 str.format() 格式化數字的多種方法:

>>> 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 {:,} 1,000,000 以逗號分隔的數字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指數記法
13 {:>10d}         13 右對齊 (默認, 寬度為10)
13 {:<10d} 13 左對齊 (寬度為10)
13 {:^10d}     13 中間對齊 (寬度為10)
11
'{: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 分別是二進位、十進位、八進制、十六進制。

此外我們可以使用大括弧 {} 來轉義大括弧,如下實例:

實例

#!/usr/bin/python # -*- coding: UTF-8 -*- print ("{} 對應的位置是 {{0}}".format("zaixian"))

輸出結果為:

zaixian 對應的位置是 {0}

Python 字串 Python 字串