Python的字符串格式化有两种方式: 百分号方式、format方式
1、百分号方式(中括号内的参数是可选的。)
%[(name)][flags][width].[precision]typecode
对象:
进制:
计数法:
特殊:
常用例子:
1 g1 = "i am %s age %d" % ("handsomeboy", 18) 2 3 g2 = "i am %(pp).2f" % {"pp": 23.425556, } 4 5 g3= "i am %(name)s age %(age)d" % {"name": "handsomeboy", "age": 16}
2、Format方式
[[fill]align][sign][#][0][width][,][.precision][type]
常用例子:
1 g1 = "i am {}, age {}, {}".format("seven", 18, ‘jhon‘)#位置 2 3 g2 = "i am {}, age {}, {}".format(*["seven", 18, ‘jhon‘])#解包 4 5 g3= "i am {0}, age {1}, really {0}".format("seven", 18)#数字 6 g4 = "i am {name}, age {age}, really {name}".format(name="seven", age=18)#字典 7 g5 = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])#索引方式 8 9 g6 = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1) 10 11 g7 = "i am {:s}, age {:d}".format(*["seven", 18]) 12 13 g8 = "i am {name:s}, age {age:d}".format(name="seven", age=18) 14 15 g9= "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
原文:http://www.cnblogs.com/yongliang/p/6486561.html