python 字符串格式化 ( 百分号 & format )
Python的字符串格式化有两种方式: 百分号方式、format方式
百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存。
----百分号
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 tpl = "i am %s" % "alex" 2 #i am alex 3 4 tpl = "i am %s age %d" % ("alex", 18) 5 #i am alex age 18 6 7 tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18} 8 #i am alex age 18 9 10 tpl = "percent %.2f" % 99.97623 11 #percent 99.98 12 13 tpl = "i am %(pp).2f %%" % {"pp": 123.425556, } 14 #i am 123.43 %
----format
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 tpl = "i am {}, age {}, {}".format("seven", 18, 'alex') 2 #i am seven, age 18, alex 3 tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex']) 4 #i am seven, age 18, alex 5 tpl = "i am {0}, age {1}, really {0}".format("seven", 18) 6 #i am seven, age 18, really seven 7 tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18]) 8 #i am seven, age 18, really seven 9 tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18) 10 #i am seven, age 18, really seven 11 tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18}) 12 #i am seven, age 18, really seven 13 tpl = "i am {0[0]}, age {1[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]) 14 #i am 1, age 22, really 3 15 tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1) 16 #i am seven, age 18, money 88888.100000 17 tpl = "i am {:s}, age {:d}".format(*["seven", 18]) 18 #i am seven, age 18 19 tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18) 20 #i am seven, age 18 21 tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18}) 22 #i am seven, age 18 23 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) 24 #numbers: 1111,17,15,f,F, 1587.623000% 25 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) 26 #numbers: 1111,17,15,f,F, 1587.623000% 27 tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15) 28 #numbers: 1111,17,15,f,F, 1500.000000% 29 tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15) 30 #numbers: 1111,17,15,f,F, 1500.000000% 31 import math 32 print('The value of PI is approximately {}.'.format(math.pi)) 33 #The value of PI is approximately 3.14159265359. 34 print('The value of PI is approximately {!r}.'.format(math.pi)) 35 #The value of PI is approximately 3.141592653589793. 36 print('The value of PI is approximately {0:.3f}.'.format(math.pi)) 37 #The value of PI is approximately 3.142. 38 table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} 39 for name, phone in table.items(): 40 print('{0:10} ==> {1:10d}'.format(name, phone)) 41 ''' 42 Dcab ==> 7678 43 Jack ==> 4098 44 Sjoerd ==> 4127 45 ''' 46 table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} 47 print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(table)) 48 #Jack: 4098; Sjoerd: 4127; Dcab: 8637678