格式化包括:百分号方式和format方式
1.百分号
- %s (%.4s 表示截取了4个字符)
传单个值:
例如:
print('i am %s sex boy is ljj'%123)
运行结果:
i am 123 sex boy is ljj Process finished with exit code 0
传多个值:
print('i am %s sex boy is %s'%('13','ss'))
运行结果:
i am 13 sex boy is ss Process finished with exit code 0
- %d (只能传数字)
a= 'i am %s, she is %d'%('xm',123) print(a)
运行结果:
i am xm, she is 123 Process finished with exit code 0
-打印浮点数
a= 'abc %.2f'%99.45678 # .2表示保留小数点后2位(四舍五入) print(a)
运行结果:
abc 99.46
Process finished with exit code 0
-打印百分比
a= 'abc %.2f %%'%99.45678 print(a)
运行结果:
abc 99.46 %
Process finished with exit code 0
-键值
a= "i am %(name)s ,and age is %(age)d" % {"name":"ljj","age":18} print(a)
运行结果:
i am ljj ,and age is 18 Process finished with exit code 0
-其他方法
a= "i am %(name)-60s aabbcc" % {"name":"ljj"} #左对齐60格(+右对齐) print(a)
运行结果:
i am ljj aabbcc
Process finished with exit code 0
2.format方式
-传值
a= "i am {},age {},{}" .format("xm",18,123) print(a)
运行结果:
i am xm,age 18,123
Process finished with exit code 0
-根据索引取值
a= "i am {1},age {0}" .format("xm",18,123) print(a)
运行结果:
i am 18,age xm
Process finished with exit code 0
-
a= "i am {name},age {age} " .format(name="xm",age=18) print(a)
运行结果:
i am xm,age 18
Process finished with exit code 0