免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
Python學(xué)習(xí)教程:Python3之字符串格式化format函數(shù)詳解(上)

Python學(xué)習(xí)教程:Python3之字符串格式化format函數(shù)詳解(上)

概述

在Python3中,字符串格式化操作通過format()方法或者f’string’實現(xiàn)。而相比于老版的字符串格式化方式,format()方法擁有更多的功能,操作起來更加方便,可讀性也更強。該函數(shù)將字符串當(dāng)成一個模板,通過傳入的參數(shù)進行格式化,并且使用大括號{}作為特殊字符代替%。

位置設(shè)定

默認位置

不指定格式化位置,按照默認順序格式化

S = 'I {} {}, and I'am learning'.format('like', 'Python')
print(S)

示例結(jié)果:

I like Python, and I'am learning

設(shè)置位置

設(shè)置數(shù)字順序指定格式化的位置

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)

示例結(jié)果:

I like Python, and I'am learning
I Python like Python, and I'am learning

設(shè)置關(guān)鍵字

設(shè)置關(guān)鍵字指定格式化的內(nèi)容

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)

示例結(jié)果:

I like Python, and I'am learning
I Python like, and I'am learning

參數(shù)傳遞

我們可以傳入各種類型參數(shù)格式化字符串,即不限于字符串變量或數(shù)字等。

元組傳參

利用元組傳參,傳參形式 *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)

示例結(jié)果:

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)

示例結(jié)果:

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)

示例結(jié)果:

I like Lerning, and I'am learning

下期的Python學(xué)習(xí)教程會繼續(xù)為大家更新!

本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
python print() 函數(shù)的格式化字符串輸出
python教程 --.Python 列表Lis
Python中format函數(shù)用法
python菜鳥教程學(xué)習(xí)12:輸入輸出
【Python】入門了解
4個Python隱藏技巧,你get了嗎?
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服