Python3之字符串格式化format函數詳解(上)


概述

在Python3中,字符串格式化操作通過format()方法或者f’string’實現。而相比於老版的字符串格式化方式,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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM