python 格式化输出%和format
1 %用法
1.1整數的輸出
%o —— oct 八進制
%d —— dec 十進制
%x —— hex 十六進制
1.2浮點數輸出
%f ——默認保留小數點后面六位有效數字
%.3f,保留3位小數位
%e ——默認保留小數點后面六位有效數字,指數形式輸出
%.3e,保留3位小數位,使用科學計數法
%g ——在保證六位有效數字的前提下,使用小數方式,否則使用科學計數法
%.3g,保留3位有效數字,使用小數或科學計數法
1.3round四舍五入
round(number[, ndigits])
參數:
number - 這是一個數字表達式。
ndigits - 表示從小數點到最后四舍五入的位數。默認值為0。
返回值
該方法返回x的小數點舍入為n位數后的值。
1.4字符串輸出
%s
%10s——右對齊,占位符10位
%-10s——左對齊,占位符10位
%.2s——截取2位字符串
%10.2s——10位占位符,截取兩位字符串
輸出結果:
print(’%s’ % ‘hello world’)
print(’%s’ % 1)
print(’%20s’ % ‘hello world’)
print(’%-20s’ % ‘hello world’)
print(’%.2s’ % ‘hello world’)
print(’%10.2s’ % ‘hello world’)
print(’%-10.2s’ % ‘hello world’)
常見格式:
常見轉義字符:
2 format用法
format()功能更強大,該函數把字符串當成一個模板,通過傳入的參數進行格式化,并且使用大括號‘{}’作為特殊字符代替‘%’
2.1位置匹配
(1)不帶編號,即“{}”
(2)帶數字編號,可調換順序,即“{1}”、“{2}”
(3)帶關鍵字,即“{a}”、“{tom}”
print('{} {}'.format('hello','world')) print('{0} {1}'.format('hello', 'world')) print('{0} {1} {0}'.format('hello','world')) print('{1} {1} {0}'.format('hello','world')) print('{a} {tom} {a}'.format(tom='hello',a='world'))輸出結果
hello world
hello world
hello world hello
world world hello
world hello world
輸出結果:
a, b, c
a, b, c
c, b, a
c, b, a
abracadabra
輸出結果:
2010-07-04 12:15:34
2.2左中右對齊及位數補全
(1)< (默認)左對齊、> 右對齊、^ 中間對齊、= (只用于數字)在小數點后進行補齊
(2)取位數“{:4s}”、"{:.2f}"等
points=19 total=22 print('Correct answers: {:.2%}'.format(points/total)) print('{} is {:.2f}'.format(1.123,1.123)) print('{0} is {0:>10.2f}'.format(1.123)) print('{:+f}; {:+f}'.format(3.14, -3.14)) # 總是顯示符號 print('{:,}'.format(1234567890))輸出結果:
Correct answers: 86.36%
1.123 is 1.12
1.123 is 1.12
+3.140000; -3.140000
1,234,567,890
總結
以上是生活随笔為你收集整理的python 格式化输出%和format的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IIS安装2个SSL_顶级域名0元撸-免
- 下一篇: cad和python哪个好学_对纯外行人