Python占位符总结:%方式和format方式,,Python中,我们


Python中,我们在预定义某类具有相似格式的变量或者输出一句含有多个变量的提示语句时,往往用到占位符,而占位符有两种表达方式:

%方式:

下面这段代码摘自matplotlib的_init_.py文件中class RcParams的定义:

 1   msg_depr = "%s is deprecated and replaced with %s; please use the latter." 2   msg_depr_set = ("%s is deprecated. Please remove it from your " 3                     "matplotlibrc and/or style files.") 4   msg_depr_ignore = "%s is deprecated and ignored. Use %s instead." 5   msg_obsolete = ("%s is obsolete. Please remove it from your matplotlibrc " 6                     "and/or style files.") 7   msg_backend_obsolete = ("The {} rcParam was deprecated in version 2.2.  In" 8                             " order to force the use of a specific Qt binding," 9                             " either import that binding first, or set the "10                             "QT_API environment variable.")

其中,%s表示此展位符可用相关字符串代替,这是一个比较简单的实例,%方式的占位符具体格式为:

 %[(name)][flags][width].[precision]typecode

(name) 可选,用于选择指定的keyflags 可选,可供选择的值有:+ 右对齐;正数前加正好,负数前加负号;- 左对齐;正数前无符号,负数前加负号;空格 右对齐;正数前加空格,负数前加负号;0 右对齐;正数前无符号,负数前加负号;用0填充空白处width 可选,占有宽度.precision 可选,小数点后保留的位数typecode 必选s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置c,整数:将数字转换成其unicode对应的值,10进制范围为0 <= i <= 1114111(py27则只支持0-255);字符:将字符添加到指定位置o,将整数转换成 八 进制表示,并将其格式化到指定位置x,将整数转换成十六进制表示,并将其格式化到指定位置d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)F,同上g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)%,当字符串中存在格式化标志时,需要用 %%表示一个百分号

注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式

tpl = "i am %s" % "alex" print(tpl)
tpl = "i am %s age %d" % ("alex", 18) print(tpl)
tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18} print(tpl)
tpl = "percent %.2f" % 99.97623 print(tpl)
tpl = "i am %(pp).2f" % {"pp": 123.425556, } print(tpl)
tpl = "i am %(pp).2f %%" % {"pp": 123.425556, } print(tpl)
i am alex
i am alex age 18
i am alex age 18
percent 99.98
i am 123.43
i am 123.43 %

format方式:

以下是同时输出字典roll_dict的key-value对的format表达方式:

total_times = 1000
roll_dict={"1":56, "2":65, "3":458, "4":25}
for i, result in roll_dict.items():
print(‘点数是{}的次数是:{},频率是:{}‘ .format(i, result, result/total_times))

点数是1的次数是:56,频率是:0.056
点数是2的次数是:65,频率是:0.065
点数是3的次数是:458,频率是:0.458
点数是4的次数是:25,频率是:0.025

如上述例子所示:forma占位需要结合{}使用,{}中可以带入相关变量的相关参数,上述例子中{}是空白,未指定类型,则默认是None,表示实际变量i,result,result/total_times依次取代前面三个{}。

format的{}格式具体如下:

[[fill]align][sign][#][0][width][,][.precision][type]

fill 【可选】空白处填充的字符align 【可选】对齐方式(需配合width使用)<,内容左对齐>,内容右对齐(默认)=,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字^,内容居中sign 【可选】有无符号数字+,正号加正,负号加负;-,正号不变,负号加负;空格 ,正号空格,负号加负;# 【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示, 【可选】为数字添加分隔符,如:1,000,000width 【可选】格式化位所占宽度.precision 【可选】小数位保留精度type 【可选】格式化类型传入” 字符串类型 “的参数s,格式化字符串类型数据空白,未指定类型,则默认是None,同s传入“ 整数类型 ”的参数 b,将10进制整数自动转换成2进制表示然后格式化c,将10进制整数自动转换为其对应的unicode字符d,十进制整数o,将10进制整数自动转换成8进制表示然后格式化;x,将10进制整数自动转换成16进制表示然后格式化(小写x)X,将10进制整数自动转换成16进制表示然后格式化(大写X)传入“ 浮点型或小数类型”的参数e, 转换为科学计数法(小写e)表示,然后格式化;E, 转换为科学计数法(大写E)表示,然后格式化;f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;g, 自动在e和f中切换G, 自动在E和F中切换%,显示百分比(默认显示小数点后6位)

 1 tpl = "i am {}, age {}, {}".format("seven", 18, ‘alex‘) 2 print(tpl) 3  4 tpl = "i am {}, age {}, {}".format(*["seven", 18, ‘alex‘]) 5 print(tpl) 6  7 tpl = "i am {0}, age {1}, really {0}".format("seven", 18) 8 print(tpl) 9 10 tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])11 print(tpl)12 13 tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)14 print(tpl)15 16 tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})17 print(tpl)18 19 tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])20 print(tpl)21 22 tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)23 print(tpl)24 25 tpl = "i am {:s}, age {:d}".format(*["seven", 18])26 print(tpl)27 28 tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)29 print(tpl)30 31 tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})32 print(tpl)33 34 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)35 print(tpl)36 37 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)38 print(tpl)39 40 tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)41 print(tpl)42 43 tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)44 print(tpl)

i am seven, age 18, alex
i am seven, age 18, alex
i am seven, age 18, really seven
i am seven, age 18, really seven
i am seven, age 18, really seven
i am seven, age 18, really seven
i am 1, age 2, really 3
i am seven, age 18, money 88888.100000
i am seven, age 18
i am seven, age 18
i am seven, age 18
numbers: 1111,17,15,f,F, 1587.623000%
numbers: 1111,17,15,f,F, 1587.623000%
numbers: 1111,17,15,f,F, 1500.000000%
numbers: 1111,17,15,f,F, 1500.000000%

从上述例子中可以看出{}在语句中出现的位置依次与format中变量出现的位置从左到右依次对应,但如果{}中有整型数据,则整型数据值表示format中元素的索引位置:

1 tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])2 print(tpl)

输出为:

i am 1, age 2, really 3

如果改成:

1 tpl = "i am {0}, age {1[1]}, really {1[2]}".format([1, 2, 3], [11, 22, 33])2 print(tpl)

则输出为:
i am [1, 2, 3], age 22, really 33


此种方式更显灵活。


Python占位符总结:%方式和format方式

评论关闭