python3中字符串格式化有兩種方法:%和format

成都創(chuàng)新互聯(lián)公司主要從事網站設計制作、網站設計、網頁設計、企業(yè)做網站、公司建網站等業(yè)務。立足成都服務臨翔,十載網站建設經驗,價格優(yōu)惠、服務專業(yè),歡迎來電咨詢建站服務:028-86922220
一、%
在%操作符左側放置一個需要進行格式化的字符串,這個字符串帶有一個或多個嵌入的轉換目標,都以%開頭,如%s,%d,%f。
在%操作符右側放置一個對象,這些對象將會插入到左側想讓python進行格式化字符串的一個轉換目標的位置上。
案例:
>>> 'this is a %s' % 'test' 'this is a test' >>> >>> 'shuangji %d.this is a %s' % (666,'test') #右側有多個值時用括號括起來 'shuangji 666.this is a test' >>> >>> '%s--%s--%s' % (666,231.51241,[1,2,3]) #python中任何類型都可以轉換為字符串。實例中左側都是%s,會將右側中的對象轉換為字符串(重新創(chuàng)建)。 '666--231.51241--[1, 2, 3]' >>>
%左側通用結構是 %[(name)][flags][width寬度][.precision精度]typecode,-左對齊,+正負號,0補零
>>> x=1234
>>> test='%d...%-6d...%06d'%(x,x,x) #-號左對齊。0不足位數補零
>>> test
'1234...1234 ...001234'
>>> x=12.126435787654123 #浮點數的表示方法
>>> '%e|%f|%g'%(x,x,x)
'1.212644e+01|12.126436|12.1264'
>>> '%-6.2f|%06.2f|%+06.1f'%(x,x,x) #6.2表示總有6位數,2位小數
'12.13 |012.13|+012.1'
>>> '%-6.2f|%06.2f|%.*f'%(x,x,4,x) #此處*表示精度,將4給*后,x是替代值
'12.13 |012.13|12.1264'
>>>
>>> '%(a)s %(b)s %(c)s %(d)s' % ({'a':'this','b':'is','c':'a','d':'test'}) #基于字典的格式化,是使用鍵值的。
'this is a test'二、format方法
>>> 'this {} a {}'.format('is','test') #默認1對1,多1不可,缺1不可
'this is a test'
>>> 'this {1} a {0}'.format('is','test') #{}通過位置找出替換目標及插入的參數
'this test a is'
>>> 'this {x} a {y}'.format(x='is',y='test') #{}通過關鍵字找出替換目標及插入的參數
'this is a test'
>>> 'this {x} a {0}'.format('is',x='test') #兩者都有
'this test a is'
>>>
>>> 'this {1[spam]} test of {0.platform}'.format(sys,{'spam':'is'}) #0表示第一個位置,.platform 表示位置或關鍵字所引用的對象屬性:sys.platform。
'this is test of linux'
>>>format格式結構{fieldname!conversionflag:formatspec},fieldname表示參數的一個數字位置或關鍵字,conversionflag可以是r,s,a對應repr/str/ascii內置函數的一次調用,formatspec指定了如何表示該值:字段寬度、對齊方式、補零、小數精度等。冒號后的formatspec組成形式有:[[fill]align對齊方式][sign][#][0][width寬度][.precision精度][typecode]
>>> '{0:>10}={1:<10}'.format('test',12.62424) #字段寬度為10個,>右對齊,<左對齊
' test=12.62424 '
>>> import sys
>>> '{0.platform:>10}={1[item]:<10}'.format(sys,dict(item='laptop')) #使用位置.屬性的方法替換值
' linux=laptop '
>>>
>>> '{0:.2f}'.format(1/3.0)
'0.33'
>>> '{0:.{1}f}'.format(1/3.0,4) #動態(tài)的從參數列表獲取精度位數
'0.3333'
>>> '{%.*f}'%(6,1/3.0) #動態(tài)的使用%從參數列表獲取精度位數
'{0.333333}'
>>>高級用法
>>> msg='this {a} a {b} for python,The No.{c}'.format(**{'a':'is','b':'a','c':1}) #使用字典形式來格式化,必須加入兩個 *號和大括號
>>> print(msg)
this is a a for python,The No.1
>>>
>>> msg='this {:s} a {:s} for python,The No.{:d}'.format('is','test',1)
>>> print(msg)
this is a test for python,The No.1
>>>
>>> msg='this {:s} a {:s} for python,The No.{:d}'.format(*['is','test',1]) #列表形式加入一個*號,*表示將列表中的元素,遍歷出來,類似上面一個列子
>>> print(msg)
this is a test for python,The No.1
>>>
新聞名稱:python字符串格式化
網站鏈接:http://chinadenli.net/article16/jggidg.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、網站導航、Google、關鍵詞優(yōu)化、網站設計公司、網站收錄
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)