标签:
Python的字符串格式化有两种方式: 百分号方式、format方式
百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存。
1、百分号方式
%[(name)][flags][width].[precision]typecode
注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式
常用的格式化:
s1 = "i am %s" % "wenchong" s2 = "i am %s age %d" % ("wenchong", 8) s3 = "i am %(name)s age %(age)d" % {"name": "wenchong", "age": 8} s4 = "percent %.2f" % 99.999999 s5 = "i am %(pp).2f" % {"pp": 123.425556, } s6 = "i am %(pp).2f %%" % {"pp": 123.425556, }
输出结果:
s1: i am wenchong s2: i am wenchong age 8 s3: i am wenchong age 8 s4: percent 100.00 s5: i am 123.43 s6: i am 123.43 %
2、format 方式
[[fill]align][sign][#][0][width][,][.precision][type]
常用格式化:
s1 = "i am {}, age {}, {}".format("wenchong", 8, ‘WenChong‘) s2 = "i am {}, age {}, {}".format(*["wenchong", 1, ‘WenChong‘]) s3 = "i am {0}, age {1}, really {0}".format("WenChong", 8) s4 = "i am {0}, age {1}, really {0}".format(*["WenChong", 8]) s5 = "i am {name}, age {age}, really {name}".format(name="WenChong", age=8) s6 = "i am {name}, age {age}, really {name}".format(**{"name": "WenChong", "age": 18}) s7 = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]) s8 = "i am {:s}, age {:d}, money {:f}".format("WenChong", 8, 88888.1) s9 = "i am {:s}, age {:d}".format(*["WenChong", 8]) s10 = "i am {name:s}, age {age:d}".format(name="WenChong", age=8) s11 = "i am {name:s}, age {age:d}".format(**{"name": "WenChong", "age": 8}) s12 = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) s13 = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) s14 = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15) s15 = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
输出结果:
s1: i am wenchong, age 8, WenChong s2: i am wenchong, age 1, WenChong s3: i am WenChong, age 8, really WenChong s4: i am WenChong, age 8, really WenChong s5: i am WenChong, age 8, really WenChong s6: i am WenChong, age 18, really WenChong s7: i am 1, age 2, really 3 s8: i am WenChong, age 8, money 88888.100000 s9: i am WenChong, age 8 s10: i am WenChong, age 8 s11: i am WenChong, age 8 s12: numbers: 1111,17,15,f,F, 1587.623000% s13: numbers: 1111,17,15,f,F, 1587.623000% s14: numbers: 1111,17,15,f,F, 1500.000000% s15: numbers: 1111,17,15,f,F, 1500.000000%
标签:
原文地址:http://www.cnblogs.com/wenchong/p/5816352.html