1. 程式人生 > 實用技巧 >python中字串的格式化

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'