日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python3中format函数列表_Python3之字符串格式化format函数详解(上)

發(fā)布時(shí)間:2023/12/10 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python3中format函数列表_Python3之字符串格式化format函数详解(上) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

173.jpg

概述

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

位置設(shè)定

默認(rèn)位置

不指定格式化位置,按照默認(rèn)順序格式化

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

# 定義一個(gè)元組

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

字典傳參

# 定義一個(gè)字典

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

列表傳參

# 定義一個(gè)列表

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

總結(jié)

以上是生活随笔為你收集整理的python3中format函数列表_Python3之字符串格式化format函数详解(上)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。