python基础---->字符串格式化
关于字符串格式化
Python的字符串格式化有两种方式: %方式、format方式;
百分号的方式相对来说比较过时,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存。
1、百分号方式
官方文档对其说明的格式,更详细请参考:[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, }
2、Format方式
[[fill][align][sign][#][0][width][,][.precision][type] fill 【可选】空白处填充的字符 align 【可选】对齐方式(需配合width使用) sign 【可选】有无符号数字 # 【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示 , 【可选】为数字添加分隔符,如:1,000,000 width 【可选】格式化位所占宽度 .precision 【可选】小数位保留精度 type 【可选】格式化类型
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)