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
看完上述內容,你們掌握Python3中怎么使用format函數格式化字符串的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注創新互聯-成都網站建設公司行業資訊頻道,感謝各位的閱讀!
網頁題目:Python3中怎么使用format函數格式化字符串-創新互聯
分享網址:http://m.kartarina.com/article30/cdsopo.html
成都網站建設公司_創新互聯,為您提供網站內鏈、App開發、動態網站、微信小程序、響應式網站、外貿建站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯