在Python3中,字符串格式化操做經過format()方法或者f’string’實現。而相比於老版的字符串格式化方式,format()方法擁有更多的功能,操做起來更加方便,可讀性也更強。該函數將字符串當成一個模板,經過傳入的參數進行格式化,而且使用大括號{}
做爲特殊字符代替%
。python
不指定格式化位置,按照默認順序格式化函數
S = 'I {} {}, and I\'am learning'.format('like', 'Python') print(S)
示例結果:ui
I like Python, and I'am learning
設置數字順序指定格式化的位置spa
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)
示例結果:code
I like Python, and I'am learning I Python like Python, and I'am learning
設置關鍵字指定格式化的內容叉車維修租賃orm
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)
示例結果:token
I like Python, and I'am learning I Python like, and I'am learning
咱們能夠傳入各類類型參數格式化字符串,即不限於字符串變量或數字等。字符串
利用元組傳參,傳參形式 *tuple
get
# 定義一個元組 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)
示例結果:string
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