1、字符串格式化
+右对齐
-左对齐
1 # -*- coding:utf-8 -*- 2 name = "zf" 3 print("我是%s" % name) 4 5 # ---------- 6 p = 99.9784224 7 print("percent %.2f" % p) 8 9 # --------- 10 p = 99.9734224 11 print("percent %.2f%%" % p) 12 # --------- 13 tp = "I am %(name)s age is %(age)d" % {"name": "zf", "age": 18} 14 print(tp)
2、字符串format格式化
常用格式
1 # -*- coding:utf-8 -*- 2 tp = "I am {} age is {} ".format("zf", 18) # 默认元组 3 print(1, tp) 4 tp = "I am {name:s} age is {age} ".format(name="zf", age=18) 5 print(2, tp) 6 tp = "I am {name} age is {age} ".format(**{"name": "zf", "age": 18}) 7 print(3, tp) 8 tp = "I am {:s} age is {:d} ".format("zf", 18) 9 print(4, tp) 10 tp = "I am {1:d} age is {0:s} ".format(*["zf", 18]) 11 print(5, tp) 12 l = ["zf", 18] 13 tp = "I am {1:d} age is {0:s} ".format(*l) 14 print(6, tp)