在Python3中,字符串格式化操作通過format()方法,format()方法擁有更多的功能,操作起來更加方便。該函數將字符串當成一個模板,通過傳入的參數進行格式化,並且使用大括號{}
作為特殊字符代替%
。
位置設定
不指定位置的時候,使用默認位置
不指定格式化位置,按照默認順序格式化
S = 'I {} {}, and I\'am learning'.format('like', 'Python') print(S)
示例結果:
I like Python, and I'am learning
設置位置
設置數字順序指定格式化的位置
S = 'I {0} {1}, and I\'am learning'.format('like', 'Python') print(S) # 打亂順序 S = 'I {1} {0} {1}, and I\'am learning'.format('like', 'Python') print(S)
示例結果:
I like Python, and I'am learning I Python like Python, and I'am learning
設置關鍵字
S = 'I {l} {p}, and I\'am learning'.format(p='Python', l='like') print(S) S = 'I {p} {l}, and I\'am learning'.format(p='Python', l='like') print(S)
示例結果:
I like Python, and I'am learning I Python like, and I'am learning
參數傳遞
我們可以傳入各種類型參數格式化字符串,即不限於字符串變量或數字等。
元組傳參
利用元組傳參,傳參形式 *tuple
# 定義一個元組 T = 'like', 'Python' # 不指定順序 S = 'I {} {}, and I\'am learning'.format(*T) print(S) # 指定順序 S = 'I {0} {1}, and I\'am learning'.format(*T) print(S)
示例結果:
I like Python, and I'am learning I like Python, and I'am learning
字典傳參
# 定義一個字典 D = {'l':'like', 'p':'Python'} # 指定鍵確定順序 S = 'I {l} {p}, and I\'am learning'.format(**D) print(S)
示例結果:
I like Python, and I'am learning
列表傳參
# 定義一個列表 L0 = ['like', 'Python'] L1 = [' ', 'Lerning'] # `[]`前的0、1用於指定傳入的列表順序 S = 'I {0[0]} {1[1]}, and I\'am learning'.format(L0, L1) print(S)
示例結果:
I like Lerning, and I'am learning
格式限定符
format通過豐富的的“格式限定符”(語法是 {}
中帶:
號)對需要格式的內容完成更加詳細的制定。
進制轉換
我們可以再限定符中制定不同的字符對數字進行進制轉換的格式化,進制對應的表格:
字符 | 含義 |
---|---|
b | 二進制 |
c | Unicode 字符 |
d | 十進制整數 |
o | 八進制數 |
x | 十六進制數,a 到 f 小寫 |
X | 十六進制數,A 到 F 大寫 |
N = 99 print('{:b}'.format(N)) print('{:c}'.format(N)) print('{:d}'.format(N)) print('{:o}'.format(N)) print('{:x}'.format(N)) print('{:X}'.format(N))
示例結果:
1100011 c 99 143 63 63
填充與對齊
:
號后面帶填充的字符,只能是一個字符,不指定的話默認是用空格填充,且填充常跟對齊一起使用,^
、<
、>
分別是居中、左對齊、右對齊,后面帶寬度。
N = 99 print('{:>8}'.format(N)) print('{:->8}'.format(N)) print('{:-<8}'.format(N)) print('{:-^8}'.format(N))
示例結果:叉車租賃
99 ------99 99------ ---99---
精度
:
號后面設置精度(以.
開始加上精度),然后用f結束,若不是設置,默認為精度為6,自動四舍五入,可帶符號顯示數字正負標志。
N = 99.1234567 NN = -99.1234567 print('{:f}'.format(N)) print('{:.2f}'.format(N)) print('{:+.2f}'.format(N)) print('{:+.2f}'.format(NN))
示例結果:
99.123457 99.12 +99.12 -99.12
轉義
我們可以使用大括號 {} 來轉義大括號。
p = 'Python' S = 'I like {}, and {{0}}'.format(p) print(S)
示例結果:
I like Python, and {0}