...">
瀏覽量:124次
python format函數(shù)的用法是什么呢?不知道的小伙伴來看看陽泰小編今天的分享吧!
python format函數(shù)用法詳解:
1、位置
print("hello {0}, this is {1}.".format("world", "python"))? # 根據(jù)位置下標(biāo)進行填充
print("hello {}, this is {}.".format("world", "python"))? # 根據(jù)順序自動填充
print("hello {0}, this is {1}. {1} is a new language.".format("world", "python"))? # 同一參數(shù)可以填充多次
輸出:
hello world, this is python.
hello world, this is python.
hello world, this is python. python is a new language.
2、key
obj = "world"
name = "python"
print("hello {obj}, this is {name}.".format(obj = obj, name = name))
輸出:
hello world, this is python.
3、列表
list = ["world", "python"]
print("hello {names[0]}, this is {names[1]}.".format(names = list))
輸出:
hello world, this is python.
4、字典
dict = {"obj":"world", "name":"python"}
print("hello {names[obj]}, this is {names[name]}.".format(names = dict))
輸出:
hello world, this is python.
注意:
訪問字典的 key,不用引號。
5、類屬性
class Names():
? ? obj = "world"
? ? name = "python"
print("hello {names.obj}, this is {names.name}.".format(names = Names))
輸出:
hello world, this is python.
6、魔法參數(shù)
args = [",", "inx"]
kwargs = {"obj": "world", "name": "python"}
print("hello {obj}{} this is {name}.".format(*args, **kwargs))
輸出:
hello world, this is python.
注意:
這里的 format(*args, **kwargs) 等價于 format(",", "inx", obj = "world", name = "python")。
二、數(shù)字格式化
三、其他用法
1、轉(zhuǎn)義
print("{{hello}} {{{0}}}".format("world"))
輸出:
{hello} {world}
2、format 作為函數(shù)變量
name = "python"
hello = "hello, welcome to {} world!".format
print(hello(name))
輸出:
hello, welcome to python world!
3、格式化 datatime
from datetime import datetime
now = datetime.now()
print("{:%Y-%m-%d %X}".format(now))
輸出:
2020-12-15 19:46:24
4、{}內(nèi)嵌{}
print("hello {0:>{1}} ".format("world", 10))
輸出:
hello? ? ? world
[聲明]本網(wǎng)轉(zhuǎn)載網(wǎng)絡(luò)媒體稿件是為了傳播更多的信息,此類稿件不代表本網(wǎng)觀點,本網(wǎng)不承擔(dān)此類稿件侵權(quán)行為的連帶責(zé)任。故此,如果您發(fā)現(xiàn)本網(wǎng)站的內(nèi)容侵犯了您的版權(quán),請您的相關(guān)內(nèi)容發(fā)至此郵箱【779898168@qq.com】,我們在確認后,會立即刪除,保證您的版權(quán)。
官網(wǎng)優(yōu)化
整站優(yōu)化
渠道代理
400-655-5776