字符串格式化站位 ——format

发布时间 2023-11-27 22:23:02作者: 坚持坚持再一次坚持
s='helloworld'
print('{0:*<20}'.format(s)) #0是format的索引 并且format的元素只有一个,输出字符串左对齐,右边补充以20为单位的*
#结果为:helloworld**********
print('{0:*>20}'.format(s))
#结果为:**********helloworld
print('{0:*^20}'.format(s))
#输出结果为:*****helloworld*****

#另外一种居中输出的方式 .center
print(s.center(20,'*'))
#输出结果为:*****helloworld*****
#前卫分隔符 ','format(只适用于浮点型个整数型)
print('{0:,}'.format(987564321.12345678))
#输出结果为:987,564,321
#浮点部分的精度
print('{0:.3f}'.format(987564321.12345678))
#输出结果为:987564321.123
print('{0:.5}'.format(s)) #5是s 中元素的长度,只输出5个元素
#输出结果为:holle
#整数类型
a=366
b=863
print('{0:b},{1:o},{0:d},{1:x}'.format(a,b)) #这里的0和1是format函数中的元素的索引,b是2进制,o是8进制,d是10进制,x是16进制
#输出结果为101101110,1537,366,35f