標籤:基於 數字 item tsp 小數 laptop 數列 asc flag
python3中字串格式化有兩種方法:%和format
一、%
在%操作符左側放置一個需要進行格式化的字串,這個字串帶有一個或多個嵌入的轉換目標,都以%開頭,如%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,會將右側中的對象轉換為字串(重新建立)。'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) #動態從參數列表擷取精度位元'0.3333'>>> '{%.*f}'%(6,1/3.0) #動態使用%從參數列表擷取精度位元'{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字串格式化