标签:
python的字符串格式化有两种方式:百分号方式,format方式
百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存。
1.百分号方式
%[(name)][flags][width].[precision]typecode
注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式
练习:
tp1 = "i am %s" % "tiantian" print(tp1)
输出结果:
i am tiantian
tp2 = "i am %s age %d" %("tiantian",19) print(tp2) tp3 = "i am %(name)s age %(age)d" % {‘name‘:‘tiantian‘,‘age‘:18} print(tp3)
输出结果:
i am tiantian age 19
i am tiantian age 18
右对齐:
tp4 = "%(name)+30s age %(age)d" % {‘name‘:‘tiantian‘,‘age‘:18} print(tp4)
输出结果:
tiantian age 18
#左对齐 tp5 = "%(name)-30s age %(age)d" % {‘name‘:‘tiantian‘,‘age‘:18} print(tp5)
输出结果:
tiantian age 18
#保留两位小数,四舍五入 tp6 = "%(a).2f" %{‘a‘:1.37834} print(tp6)
结果:
1.38
常用格式化:
tpl = "i am %s" % "alex" tpl = "i am %s age %d" % ("alex", 18) tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18} tpl = "percent %.2f" % 99.97623 # tpl = "i am %(pp).2f" % {"pp": 123.425556} print(tpl) 输出:
i am 123.43 tpl = "i am %(pp).2f %%" % {"pp": 123.425556,} print(tpl)
输出:
i am 123.43 %
标签:
原文地址:http://www.cnblogs.com/pangguoping/p/5566558.html