用法
它通过{}和:来代替传统%方式
1、使用位置参数
要点:从以下例子可以看出位置参数不受顺序约束,且可以为{},只要format里有相对应的参数值即可,参数索引从0开,传入位置参数列表可用*列表
print("{} is a student who is {}".format("haha",18))
print("{} is a student who is {}".format(18,"haha"))
print("{1} is a student who is {0}".format(18,"haha"))
print("{1}{0} is a student who is {0}".format(18,"haha"))
输出
haha is a student who is 18
18 is a student who is haha
haha is a student who is 18
haha18 is a student who is 18
2、使用关键字参数
要点:关键字参数值要对得上,可用字典当关键字参数传入值,字典前加**即可
print("{name} is a student who is {age}".format(name="haha",age=18))
print("{name}{age} is a student who is {age}".format(name="haha",age=18))
输出
haha is a student who is 18
haha18 is a student who is 18
3、填充与格式化:[填充字符][对齐方式 <^>][宽度]
前面一篇文章介绍了python中字符串补齐的三种方法,这里详细介绍格式化的方式进行字符串补齐,format方式相比其他两种方式更加灵活
右对齐,左端补齐
print('{0:*>10}'.format(10))
输出
********10
左对齐,右端补齐
print('{0:*<10}'.format(10))
输出
10********
中间对齐,两端补齐
print('{0:*^10}'.format(10))
输出
****10****
综合
print('{0:*>10}'.format(12))
print('{0:*<10}'.format(12))
print('{0:*^10}'.format(12))
输出
********12
12********
****12****
4、精度与进制{:[b|o|x|.nf]}.format(data)
对应的leetcode习题:1556. 千位分隔数
文章解析:《【字符串】1556. 千位分隔数(CPP递归、Python)》
点击名字即可跳转
print("{:.5f}".format(1/3))
print("{:.2f}".format(1/3))
print("{0:b}".format(10))
print("{0:o}".format(10))
print("{0:x}".format(10))
print("{:,}".format(123456789))
# 千分位格式化
输出
0.33333
0.33
1010
12
a
123,456,789
5、使用索引
l=["haha",18]
print('name is {0[0]} age is {0[1]}'.format(l))
输出
name is haha age is 18