python字符串格式化两种方式:百分号方式、format方式
用百分号字符串拼接
s = "i am %s , and i am %s" % ("an assassin", "a killer") print(s) s = "i am %s , age %d" % ("an assassin", 19)# %d 只能拼接数字 print(s) #输出结果: i am an assassin , and i am a killer i am an assassin , age 19
打印浮点数:
#打印浮点数 s1 = "percent % f" % 99.62375187 #小数点后默认是六位 s2 = "percent % .2f" % 99.587627138678 #可以修改几位小数 print(s1) print(s2) #输出结果: percent 99.623752 percent 99.59
打印百分比:
#打印百分百比 s = "percent % .2f %%" % 99.62375187 print(s) #输出结果: percent 99.62 %
format
s = "i am {},age {},{}".format("reese", 20, "assassin") print(s) s = "i am {2},age {0},{1}".format("reese", 20, "assassin") print(s) #输出结果: i am reese,age 20,assassin i am assassin,age reese,20