# 字符串格式化 format函数 # 通过位置参数,按照位置顺序替换前面的{}占位符 s1 = "name:{}, socre:{}".format("tom",89) # 关键字参数或命名参数 s2 = "name:{0},socre:{score} ".format("tom",score=99) # 如果是列表之类的用下标 s3 = "name:{0[0]},socre:{0[1]} ".format(("tom",78)) #对齐,冒号前面的数字表示对应的位置,后面的箭头表示斯左对齐还是右对齐 #箭头指哪边就往哪边对齐。>后面的数字表示占多少个字符,默认补空格,冒号后面可以 # 接其他字符,如*,表示不够位数,用*补齐 s4 = "{0:>2}+{1:>2}={2:<3}".format(1,1,1+1) s4 = "{0:*>2}+{1:->2}={2:a<3}".format(‘a‘,‘b‘,‘c‘) # 居中 s5 = ‘{:^30}‘.format(‘centered‘) s6 = "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42) #带进制前缀 s7 = "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42) print(s1) print(s2) print(s3) print(s4) print(s5) print(s6) print(s7)
name:tom, socre:89 name:tom,socre:99 name:tom,socre:78 *a+-b=caa centered int: 42; hex: 2a; oct: 52; bin: 101010 int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010
原文:https://www.cnblogs.com/mqhuang/p/14306243.html