python字符串方法format()如何使用
发布时间:2024-07-21 20:35:19

1、待插入值的位置、索引名称和格式用花括号表示在格式字符串中,待插入值写在format方法参数中。
2、转换标志:跟随感叹号后的单词,以相应的格式转换给定值。
格式说明符:跟随冒号后的表现,详细指定字符串的格式。
实例
>>>#指定表示方式
>>>print('indecimal:{0:d}\ninbinary:{0:b}'.format(10))
#indecimal:10
#inbinary:1010
>>>print('infixed-pointnotation:{0:f}\ninscientificnotation:{0:e}'.format(0.25))
#infixed-pointnotation:0.250000
#inscientificnotation:2.500000e-01
>>>#指定精度
>>>print("{0:.2f}".format(1/3))
#0.33
>>>#指定宽度,默认右对齐
>>>print("{0:10.2f}".format(1/4))
#0.25
>>>#指定对齐方法,默认用空间填充
>>>print("{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}".format(1/6))
#0.17
#0.17
#0.17
>>>#指定对齐方法,并指定填充字符
>>>print("{0:*<10.2f}\n{0:*^10.2f}\n{0:*>10.2f}".format(1/7))
#0.14******
#***0.14***
#******0.14以上是python字符串法format()的使用,希望对大家有所帮助。更多Python学习指导:python基础教程
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。
下一篇 python格式字符串是什么
