目錄:
1、%用法
2、format用法
一、%用法
1、整數(shù)的格式化
%o —— oct 八進(jìn)制
%d —— dec 十進(jìn)制
%x —— hex 十六進(jìn)制
例
>>> print('%o' % 20)
24
>>> print('%d' % 20)
20
>>> print('%x' % 20)
14
2、浮點(diǎn)數(shù)的格式化
%e ——保留小數(shù)點(diǎn)后面六位有效數(shù)字,指數(shù)形式輸出
%.3e,保留3位小數(shù)位,使用科學(xué)計(jì)數(shù)法
%f ——保留小數(shù)點(diǎn)后面六位有效數(shù)字
%.3f,保留3位小數(shù)位
%g ——在保證六位有效數(shù)字的前提下,使用小數(shù)方式,否則使用科學(xué)計(jì)數(shù)法
%.3g,保留3位有效數(shù)字,使用小數(shù)或科學(xué)計(jì)數(shù)法
>>> print('%f' % 1.11) # 默認(rèn)保留6位小數(shù)
1.110000
>>> print('%.1f' % 1.11) # 取1位小數(shù)
1.1
>>> print('%e' % 1.11) # 默認(rèn)6位小數(shù),用科學(xué)計(jì)數(shù)法
1.110000e+00
>>> print('%.3e' % 1.11) # 取3位小數(shù),用科學(xué)計(jì)數(shù)法
1.110e+00
>>> print('%g' % 1111.1111) # 默認(rèn)6位有效數(shù)字
1111.11
>>> print('%.7g' % 1111.1111) # 取7位有效數(shù)字
1111.111
>>> print('%.2g' % 1111.1111) # 取2位有效數(shù)字,自動轉(zhuǎn)換為科學(xué)計(jì)數(shù)法
1.1e+03
3、字符串的格式化
%s
%10s——右對齊,占位符10位
%-10s——左對齊,占位符10位
%.2s——截取2位字符串
>>> print('%s' % 'hello world') # 字符串輸出
hello world
>>> print('%20s' % 'hello world') # 右對齊,取20位,不夠則補(bǔ)位
hello world
>>> print('%-20s' % 'hello world') # 左對齊,取20位,不夠則補(bǔ)位
hello world
>>> print('%.2s' % 'hello world') # 取2位
he
>>> print('%10.2s' % 'hello world') # 右對齊,取2位
he
>>> print('%-10.2s' % 'hello world') # 左對齊,取2位
he
二、format用法
(1)不帶編號,即“{}”
(2)帶數(shù)字編號,可調(diào)換順序,即“{1}”、“{2}”
(3)帶關(guān)鍵字,即“{a}”、“{tom}”
例
>>> print('{} {}'.format('hello','world')) # 不帶字段
hello world
>>> print('{0} {1}'.format('hello','world')) # 帶數(shù)字編號
hello world
>>> print('{0} {1} {0}'.format('hello','world')) # 打亂順序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 帶關(guān)鍵字
world hello world
format進(jìn)階用法
上面的(1)格式化可以改寫成下式
f"xxxx"
可在字符串前加f以達(dá)到格式化的目的,在{}里加入對象,此為format的另一種形式:
>>> a = 'man'
>>> b = 'women'
>>> print(f'男人{(lán)}女人{(lán)}')
>>> print('男人{(lán)}女人{(lán)}'.format(a,b))
男人man女人women
男人man女人women
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

