format函数

来源:互联网 发布:windows 10版本 编辑:程序博客网 时间:2024/05/17 02:59

format 函数可以接受不限个参数,位置可以不按顺序

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序'hello world'>>> "{0} {1}".format("hello", "world")  # 设置指定位置'hello world'>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置'world hello world'
也可以设置参数:print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))# 通过字典设置参数site = {"name": "菜鸟教程", "url": "www.runoob.com"}print("网站名:{name}, 地址 {url}".format(**site))输出结果:网站名:菜鸟教程, 地址 www.runoob.com网站名:菜鸟教程, 地址 www.runoob.com

^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格

例:中文对齐方式

``
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}" #冒号前为引用format中参数的位置,0、1、2分别代表排名、学校、分数,^表示居中对齐,:与^之前的{3}代表填充内容,10为列宽
print(tplt.format('排名','学校','分数',chr(12288))) #chr(12288)为中文空格,上句中{3}表示引用这个内容
for i in range(num):
u = ulist[i]
print(tplt.format(u[0],u[1],u[2],chr(12288)))

详见:http://www.runoob.com/python/att-string-format.html

原创粉丝点击