Python format 格式化用法總結(jié)

1.接受參數(shù)個(gè)數(shù)?有無(wú)順序?

答:無(wú)限個(gè),無(wú)位置順序

示例:

>>>"{} {}".format("hello", "world") # 不設(shè)置指定位置,按默認(rèn)順序'hello world'

>>> "{0} {1}".format("hello", "world")? # 設(shè)置指定位置'hello world'

>>> "{1} {0} {1}".format("hello", "world")? # 設(shè)置指定位置'world hello world'


2.設(shè)置參數(shù)方式

變量,關(guān)鍵字,字典,列表,對(duì)象變量

示例;

# 變量

"{1} {0} {1}".format("hello", "world")?

#關(guān)鍵字

print("網(wǎng)站名:{name}, 地址 {url}".format(name="菜鳥(niǎo)教程", url="www.runoob.com")) ?

#字典

site = {"name": "菜鳥(niǎo)教程", "url": "www.runoob.com"}

print("網(wǎng)站名:{name}, 地址 {url}".format(**site))

#列表

my_list = ['菜鳥(niǎo)教程', 'www.runoob.com']

print("網(wǎng)站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必須的

#對(duì)象變量

示例:

class AssignValue(object):

? ? def __init__(self, value):

? ? ? ? self.value = value

my_value = AssignValue(6)

print('value 為: {0.value}'.format(my_value))? # "0" 是可選的


3.數(shù)字格式格式方法(很多很多)

示例:

>>> print("{:.2f}".format(3.1415926));

3.14


本文內(nèi)容總結(jié)于菜鳥(niǎo)教程,源網(wǎng)站地址

https://www.runoob.com/python/att-string-format.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容