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