python format函數(shù)的用法是什么呢?不知道的小伙伴來看看小編今天的分享吧!
python format函數(shù)用法詳解:
1、位置
print("hello {0}, this is {1}.".format("world", "python")) # 根據(jù)位置下標(biāo)進(jìn)行填充
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)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com