python字符串格式化有兩種方式:百分號方式和format方式。html
百分號方式相對來講比較老,而format方式則比較先進。python
一、百分號方式spa
%[(name)][flags][width].[precision]typecodecode
注:Python中百分號格式化是不存在自動將整數轉換成二進制表示的方式orm
經常使用格式化:htm
1 tpl = "i am %s" % "alex" 2 3 4 5 tpl = "i am %s age %d" % ("alex", 18) 6 7 8 9 tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18} 10 11 12 13 tpl = "percent %.2f" % 99.97623 14 15 16 17 tpl = "i am %(pp).2f" % {"pp": 123.425556, } 18 19 20 21 tpl = "i am %.2f %%" % {"pp": 123.425556, }
二、Format方式對象
[[fill]align][sign][#][0][width][,][.precision][type]blog
經常使用格式化:ci
1 tpl = "i am {}, age {}, {}".format("seven", 18, 'alex') 2 3 4 5 tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex']) 6 7 8 9 tpl = "i am {0}, age {1}, really {0}".format("seven", 18) 10 11 12 13 tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18]) 14 15 16 17 tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18) 18 19 20 21 tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18}) 22 23 24 25 tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]) 26 27 28 29 tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1) 30 31 32 33 tpl = "i am {:s}, age {:d}".format(*["seven", 18]) 34 35 36 37 tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18) 38 39 40 41 tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18}) 42 43 44 45 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) 46 47 48 49 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) 50 51 52 53 tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15) 54 55 56 57 tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
更多格式化操做:https://docs.python.org/3/library/string.htmlunicode