字串格式化format很牛B

來源:互聯網
上載者:User

標籤:

python的format方法可謂相當強大,它可以接受不限個參數。。。


1.通過位置來格式化字串,注意format傳入的參數的位置要正確{0}對應第1個參數,{1}對應第2個參數...

1 >>> ‘{0},{1}‘.format(‘kzc‘,18)2 ‘kzc,18‘3 >>> ‘{},{}‘.format(‘kzc‘,18)4 ‘kzc,18‘5 >>> ‘{1},{0},{1}‘.format(‘kzc‘,18)6 ‘18,kzc,18‘7 >>> 
位置映射實現

2.通過關鍵字參數,這樣就可以不關心順序問題,通過關鍵字傳入值

1 >>> ‘{name},{age}‘.format(age=18,name=‘kzc‘)2 ‘kzc,18‘
關鍵字實現

3.上面的通過關鍵字實現很像字典的key和value形式,那麼能不能通過字典來格式化字串呢?

1 dic = {‘ss‘:‘zhang‘,‘dd‘:20}2 name = "i am {ss} ,age {dd}"  name.format(ss=dic[‘ss‘],dd=dic[‘dd‘])
通過字典傳遞參數
1 dic = {‘ss‘:‘zhang‘,‘dd‘:20}2 name = "i am {ss} ,age {dd}" 3 name.format(**dic)
動態參數傳遞

4.既然format可以接受字典參數,列表也當然可以了。你的想法強大python就有多強大。。。

li=[‘awill‘,22]name = "i am {0} , age {1}"   name.format(li[0],li[1])
通過列表的索引實現
1 li=[‘awill‘,22]2 name = "i am {0} , age {1}"3 name.format(*li)
列表的動態參數
1 li=[‘awill‘,22]2 name = "i am {0[0]} , age {0[1]}"3 name.format(li)
列表變種形式

5.格式限定符

它有著豐富的的“格式限定符”(文法是{}中帶:號)
5.1 填充與對齊:

填充常跟對齊一起使用, ^、<、>分別是置中、靠左對齊、靠右對齊,後面頻寬度
:號後面帶填充的字元,只能是一個字元,不指定的話預設是用空格填充

1 >>> ‘{:>8}‘.format(‘189‘)2 ‘     189‘3 >>> ‘{:0<15}‘.format(‘awill‘)4 ‘awill0000000000‘5 >>> ‘{:*^20}‘.format(‘awill‘)6 ‘*******awill********‘
填充與對齊

 5.2 精度與類型f:

精度常跟類型f一起使用

如下:2表示長度為2的精度,f表示float類型。

1 >>> ‘{:.2f}‘.format(321.33545)#四捨五入2 ‘321.34‘
float精度

5.3 其他類型

格式化指示符可以包含一個展示類型來控制格式。

展示類型有很多:
  ‘b‘ - 二進位。將數字以2為基數進行輸出。
  ‘c‘ - 字元。在列印之前將整數轉換成對應的Unicode字串。
  ‘d‘ - 十進位整數。將數字以10為基數進行輸出。
  ‘o‘ - 八進位。將數字以8為基數進行輸出。
  ‘x‘ - 十六進位。將數字以16為基數進行輸出,9以上的位元用小寫字母。
  ‘e‘ - 冪符號。用科學計數法列印數字。用‘e‘表示冪。
  ‘g‘ - 一般格式。將數值以fixed-point格式輸出。當數值特別大的時候,用冪形式列印。
  ‘n‘ - 數字。當值為整數時和‘d‘相同,值為浮點數時和‘g‘相同。不同的是它會根據地區設定插入數字分隔字元。
  ‘%‘ - 百分數。將數值乘以100然後以fixed-point(‘f‘)格式列印,值後面會有一個百分比符號。

 1 >>> ‘{:b}‘.format(15) 2 ‘1111‘ 3 >>> type(‘{:b}‘.format(15)) 4 <class ‘str‘> 5 >>> ‘{:d}‘.format(15) 6 ‘15‘ 7 >>> ‘{:c}‘.format(15) 8 ‘\x0f‘ 9 >>> ‘{:c}‘.format(65)10 ‘A‘11 >>> ‘{:o}‘.format(15)12 ‘17‘13 >>> ‘{:x}‘.format(15)14 ‘f‘15 >>> ‘{:e}‘.format(15)16 ‘1.500000e+01‘17 >>> ‘{:g}‘.format(15)18 ‘15‘19 >>> type(‘{:g}‘.format(15))20 <class ‘str‘>21 >>> ‘{:g}‘.format(15000000000000)22 ‘1.5e+13‘23 >>> ‘{:n}‘.format(15000000000000)24 ‘15000000000000‘25 >>> ‘{:n}‘.format(15.00234342)26 ‘15.0023‘27 >>> ‘{:g}‘.format(15.00234342)28 ‘15.0023‘29 >>> ‘{:%}‘.format(0.234342)30 ‘23.434200%‘
View Code

5.4 用,號還能用來做金額的千位分隔字元。

>>> ‘{:,}‘.format(1234567890)‘1,234,567,890‘
View Code

6.通過對象屬性

1 class Person: 2   def __init__(self,name,age): 3     self.name,self.age = name,age 4     def __str__(self): 5       return ‘This guy is {self.name},is {self.age} old‘.format(self=self) 
View Code

7.一些其他用法

 1 >>> print(‘{0:*>20}‘.format(‘awill‘)) 2 ***************awill 3 >>> print(‘{0:4.2f}‘.format(1.1415926)) 4 1.14 5 >>> print(format(1.1415926,‘<10.2f‘)) 6 1.14       7 >>> print(‘{0:<10},{1:0<15}‘.format(‘awill‘,1.1415926)) 8 awill     ,1.1415926000000    9    10 #輸入形式的控制format11 a = int(raw_input(‘a:‘))12 b = int(raw_input(‘b:‘))13 print(‘%*.*f‘ % (a, b, 1.1415926))#a對應第一個*,代表輸出長度;b代表第二個*,代表輸出小數位元14 print( ‘%6.3f‘ % (1.1415926))#輸出長度為6,小數位元是3(末位四捨五入)15 16 print({array[2]}‘.format(array=range(10)))17 print({attr.__class__}‘.format(attr=2.4))18 print ({digit:*^ 10.5f}‘.format(digit=1.0/3))
雜技表演

 

字串格式化format很牛B

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.