Python的字符串格式化有两种方式: %方式、format方式;
百分号的方式相对来说比较过时,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存。
官方文档对其说明的格式,更详细请参考:[PEP-3101]
%[(name)][flags][width].[precision]typecode (name) 可选,用于选择指定的key; flags 可选; width 可选,占有宽度; .precision 可选,小数点后保留的位数; typecode 必选;百分号格式化常用实例:
exp = "i am %s" % "clint" exp = "i am %s age %d" % ("clint", 18) exp= "i am %(name)s age %(age)d" % {"name": "clint", "gender": 18} exp = "percent %.2f" % 123.456789 exp = "i am %(a).2f" % {"a": 123.4567890, } exp = "i am %.2f %%" % {"a": 123.4567890, }Format格式化常用实例:
exp = "i am {}, age {}".format("clint", 18) exp = "i am {}, age {}, {}".format(*["clint", 18, 'clinton]) exp = "i am {0}, age {1}, really {0}".format("clint", 18) exp = "i am {0}, age {1}, really {0}".format(*["clint", 18]) exp = "i am {name}, age {age}, really {name}".format(name="clint", age=18) tpl = "i am {name}, age {age}, really {name}".format(**{"name": "clint", "age": 18}) exp = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]) exp = "i am {:s}, age {:d}, money {:f}".format("clint", 18, 88888.1) exp = "i am {:s}, age {:d}".format(*["clint", 18]) tpl = "i am {name:s}, age {age:d}".format(name="clint", age=18) exp = "i am {name:s}, age {age:d}".format(**{"name": "clint", "age": 18}) exp = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) exp = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) exp = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15) exp = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)转载于:https://www.cnblogs.com/Utopia-Clint/p/10877787.html