目錄:
1、%用法
2、format用法
一、%用法
1、整數的格式化
%o —— oct 八進制
%d —— dec 十進制
%x —— hex 十六進制
例
>>> print('%o' % 20)
24
>>> print('%d' % 20)
20
>>> print('%x' % 20)
14
2、浮點數的格式化
%e ——保留小數點后面六位有效數字,指數形式輸出
%.3e,保留3位小數位,使用科學計數法
%f ——保留小數點后面六位有效數字
%.3f,保留3位小數位
%g ——在保證六位有效數字的前提下,使用小數方式,否則使用科學計數法
%.3g,保留3位有效數字,使用小數或科學計數法
>>> print('%f' % 1.11) # 默認保留6位小數
1.110000
>>> print('%.1f' % 1.11) # 取1位小數
1.1
>>> print('%e' % 1.11) # 默認6位小數,用科學計數法
1.110000e+00
>>> print('%.3e' % 1.11) # 取3位小數,用科學計數法
1.110e+00
>>> print('%g' % 1111.1111) # 默認6位有效數字
1111.11
>>> print('%.7g' % 1111.1111) # 取7位有效數字
1111.111
>>> print('%.2g' % 1111.1111) # 取2位有效數字,自動轉換為科學計數法
1.1e+03
3、字符串的格式化
%s
%10s——右對齊,占位符10位
%-10s——左對齊,占位符10位
%.2s——截取2位字符串
>>> print('%s' % 'hello world') # 字符串輸出
hello world
>>> print('%20s' % 'hello world') # 右對齊,取20位,不夠則補位
hello world
>>> print('%-20s' % 'hello world') # 左對齊,取20位,不夠則補位
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)帶數字編號,可調換順序,即“{1}”、“{2}”
(3)帶關鍵字,即“{a}”、“{tom}”
例
>>> print('{} {}'.format('hello','world')) # 不帶字段
hello world
>>> print('{0} {1}'.format('hello','world')) # 帶數字編號
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')) # 帶關鍵字
world hello world
format進階用法
上面的(1)格式化可以改寫成下式
f"xxxx"
可在字符串前加f以達到格式化的目的,在{}里加入對象,此為format的另一種形式:
>>> a = 'man'
>>> b = 'women'
>>> print(f'男人{}女人{}')
>>> print('男人{}女人{}'.format(a,b))
男人man女人women
男人man女人women
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
