当前位置: 首页 > 后端技术 > Python

Python格式用法详解

时间:2023-03-26 11:10:22 Python

一、填充字符串1、位置print("hello{0},thisis{1}.".format("world","python"))#根据位置下标填充print("hello{},thisis{}.".format("world","python"))#自动填写订单print("hello{0},thisis{1}.{1}isanewlanguage.".format("world","python"))#同一个参数可以多次填写:helloworld,thisispython.helloworld,thisispython.helloworld,thisispython.python是一门新语言。2.keyobj="world"name="python"print("hello{obj},thisis{name}.".format(obj=obj,name=name))输出:helloworld,thisispython.3.listlist=["world","python"]print("hello{names[0]},thisis{names[1]}.".format(names=list))输出:你好世界,这是python。4.字典dict={"obj":"world","name":"python"}print("你好{names[obj]},这是{names[name]}。".format(names=dict))输出:你好世界,这是python。注意:访问字典的key不带引号。5.类属性classNames():obj="world"name="python"print("hello{names.obj},thisis{names.name}.".format(names=Names))output:helloworld,这是python.6。魔法参数args=[",","inx"]kwargs={"obj":"world","name":"python"}print("你好{obj}{}这是{name}.".format(*args,**kwargs))输出:你好世界,这是python。注意:这里的format(*args,**kwargs)等同于format(",","inx",obj="world",name="python")。2.数字格式数字格式输出说明3.1415926{:.2f}3.14保留小数点后两位3.1415926{:+.2f}+3.14保留小数点后两位带符号-1{:+.2f}-1.00保留带符号小数点后两位2.71828{:.0f}3不带小数点5{:0>2d}05数字补零(左补,宽度2)5{:x<4d}5xxx数字补x(右补,width2)4)10{:x<4d}10xx数字补x(右补,宽度为4)1000000{:,}1,000,000逗号分隔的数字格式0.25{:.2%}25.00%百分比格式1000000000{:.2e}1.00e+09指数表示法13{:>10d}13右对齐(默认宽度为10)13{:<10d}13左对齐(宽度为10)13{:^10d}13中间对齐(宽度为10)11'{:b}'.format(11)1011binary11'{:d}'.format(11)11decimal11'{:o}'.format(11)13octal11'{:x}'.format(11)b十六进制11'{:#x}'.format(11)0xbhexadecimal11'{:#X}'.format(11)0xBhexadecimal3.其他用法1.转义print("{{hello}}{{{0}}}".format("world"))输出:{hello}{world}2.格式为函数变量name="python"hello="hello,welcometo{}world!".formatprint(hello(name))output:hello,welcometopythonworld!3.formatdatatimefromdatetimeimportdatetimenow=datetime.now()print("{:%Y-%m-%d%X}".format(now))输出:2020-12-1519:46:244。{}embedded{}print("hello{0:>{1}}".format("world",10))输出:helloworld4.Python格式格式化函数详解参考python格式用法