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" % 5
'5'
>>> "%5d" % 5
'    5'
>>> "%.5d" % 5
'00005'
>>> "%-5d" % 5
'5    '
>>> "%-.5d" % 5
'00005'
>>> "%d" % 5.84846548
'5'
>>> "%5d" % 5.84846548
'    5'
>>> "%.5d" % 5.84846548
'00005'
>>> "%-5d" % 5.84846548
'5    '
>>> "%-.5d" % 5.84846548
'00005'

 

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'

 

>>> "%f" % 5.2
'5.200000'
>>> "%.3f" % 5.2
'5.200'
>>> "%8.3f" % 5.2
'   5.200'
>>> "%08.3f" % 5.2
'0005.200'
>>> "%-8.3f" % 5.2
'5.200   '
>>> "%-8.5f" % 5.2
'5.20000 '
>>> "%-8.10f" % 5.2
'5.2000000000'

 

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'

 

posted @ 2020-12-26 11:57  小鲨鱼2018  阅读(162)  评论(0编辑  收藏  举报