python中字符串的格式化
作者:互联网
1、format()位置参数
>>> "abcdabdef".format() 'abcdabdef' >>> "abc{0}dabdef".format("YYYY","MMMM","OOOO") 'abcYYYYdabdef' >>> "abc{1}dabdef".format("YYYY","MMMM","OOOO") 'abcMMMMdabdef' >>> "abc{2}dabdef".format("YYYY","MMMM","OOOO") 'abcOOOOdabdef' >>> "{0}abc{2}dabdef".format("YYYY","MMMM","OOOO") 'YYYYabcOOOOdabdef' >>> "{1}abc{2}dabdef".format("YYYY","MMMM","OOOO") 'MMMMabcOOOOdabdef' >>> "{1}abc{2}dabde{0}f".format("YYYY","MMMM","OOOO") 'MMMMabcOOOOdabdeYYYYf' >>> "{1}abc{2}dabde{0}f".format("YYYY","MMMM","OOOO")
2、format()关键字参数
>>> "{x}abc{y}dabde{z}f".format(x="YYYY",y="MMMM",z="OOOO") 'YYYYabcMMMMdabdeOOOOf' >>> "{x}abc{y}dabde{z}f".format(y="YYYY",z="MMMM",x="OOOO") 'OOOOabcYYYYdabdeMMMMf' >>> "{x}abcdabdef".format(y="YYYY",z="MMMM",x="OOOO") 'OOOOabcdabdef'
3、格式化操作符 %
a、格式化字符串及其ASCII码 %c
>>> "%c" % 100 'd' >>> "%c" % 105 'i' >>> "%c" % 50 '2' >>> "%c" % 150 '\x96'
b、格式化字符串 %s
>>> "%s" % "abcde" 'abcde' >>> "%s%s" % ("abcde","xyzmn") 'abcdexyzmn' >>> str1="abc" >>> str2="opq" >>> "%s + %s" % (str1,str2) 'abc + opq'
c、格式化整数 %d
>>> "%d" % 8 '8' >>> "%d" % 8.1 '8' >>> "%d" % 8.1654 '8' >>> "%d" % 5421.871 '5421' >>> "5421.871整数部分是:%d" % 5421.871 '5421.871整数部分是:5421'
d、格式化浮点数 %f
>>> "%f" % 8 '8.000000' >>> "%f" % 8.45 '8.450000' >>> "%f" % 8.4554987984 '8.455499' >>> "%.1f" % 8.4554987984 '8.5' >>> "%.2f" % 8.4554987984 '8.46' >>> "%.5f" % 8.4554987984 '8.45550'
e、用科学计数法格式化浮点数 %e、%E
>>> "%e" % 5 '5.000000e+00' >>> "%e" % 500000000000 '5.000000e+11' >>> "%.1e" % 500000000000 '5.0e+11' >>> "%.2e" % 500000000000 '5.00e+11' >>> "%E" % 500000000000 '5.000000E+11' >>> "%.2E" % 500000000000 '5.00E+11'
标签:MMMM,YYYY,abc,格式化,format,python,OOOO,字符串 来源: https://www.cnblogs.com/liujiaxin2018/p/14192020.html