Python:字串格式化
阿新 • • 發佈:2018-12-31
字串格式化:
%:
%s 格式化為字串
%f 格式化為實數(浮點數)>>> format = "Hello, %s. %s enough for ya?" >>> values = ('world', 'Hot') >>> print format % values Hello, world. Hot enough for ya?
模板字串:>>> format = "Pi with three decimals: %.3f"//保留小數點後3個有效數字 >>> from math import pi//匯入pi的值 >>> print format % pi Pi with three decimals: 3.142
關鍵字引數(substitute):
單詞替換
單詞字母替換>>> from string import Template >>> s = Template('$x, gloriout $x!') >>> s.substitute(x = 'slurm') 'slurm, gloriout slurm!'
用$$插入$符號>>> from string import Template >>> s = Template("It's ${x}tastic!") >>> s.substitute(x = 'slurm') "It's slurmtastic!"
字典變數提供值>>> from string import Template >>> s = Template("Make $ selling $x!") >>> s.substitute(x = 'slurm') 'Make $ selling slurm!'
>>> from string import Template >>> s = Template('A $thing must never $action') >>> d = {} >>> d['thing'] = 'gentleman' >>> d['action'] = 'show his socks' >>> s.substitute(d) 'A gentleman must never show his socks'
用*作為欄位寬度或精度
>>> '%.*s' % (5, 'Guido van Rossum') 'Guido'
轉換標誌:
-:左對齊
+:在轉換值之前加上正負號
“ ”:正數之前保留空格
0:轉換值若位數不夠用0填充
>>> pi = 3.1415 >>> '%010.2f' % pi '0000003.14' >>> '%-10.2f' % pi '3.14 ' >>> '%10.2f' % pi ' 3.14' >>> '% 10.2f' % pi ' 3.14' >>> '%+10.2f' % pi ' +3.14'
字串格式化範例
width = input('Please enter width: ') price_width = 10 item_width = width - price_width header_format = '%-*s%*s' format = '%-*s%*.2f' print '=' * width print header_format % (item_width, 'Item', price_width, 'Price') print '-' * width print format % (item_width, 'Apples', price_width, 0.4) print format % (item_width, 'Pears', price_width, 0.5) print format % (item_width, 'Cantaloupes', price_width, 1.92) print format % (item_width, 'Dried Apricots (16 oz.)', price_width, 8) print format % (item_width, 'Prunes (4 lbs.)', price_width, 12)
結果顯示:
Please enter width: 35 =================================== Item Price ----------------------------------- Apples 0.40 Pears 0.50 Cantaloupes 1.92 Dried Apricots (16 oz.) 8.00 Prunes (4 lbs.) 12.00