Python 的格式化字串format函數

來源:互聯網
上載者:User

標籤:

閱讀mattkang在csdn中的部落格《飄逸的python - 增強格式化字串format函數》所做筆記

 

自從python2.6開始,新增了一種格式化字串的函數str.format(),他通過{}和:來代替%。

1、映射執行個體

In[1]: ‘{0},{1}‘.format(‘abc‘, 18)Out[1]: ‘abc,18‘In[2]: ‘{}‘.format(18)out[2]: 18In[3]: ‘{1},{0},{1}‘.format(‘abc‘, 123)out[3]: ‘123,abc,123‘In[4]: ‘{name}, {age}‘.format(age=18, name = ‘abc‘)out[4]: ‘abc, 18‘In[5]: p = [‘abc‘, 18]In[6]: ‘{0[0]}, {0[1]}‘.format(p)out[6]: ‘abc, 18‘

2、格式限定符

它有著豐富的格式限定符(文法是{}中帶:), 比如:

填充與對齊:

填充欲對其一起使用

^, <, >分別是置中,靠左對齊,靠右對齊,後跟寬度

:後面帶填充的字元, 只能是一個字元,不指定的話預設用空格填充

比如:

In[7]: ‘{:>8}‘.format(‘189‘)out[7]: ‘     189‘In[8]: ‘{:0>8}‘.format(‘189‘)out[8]: ‘00000189‘

精度與類型

精度常跟類型f一起使用

In[9]: ‘{:.2f}‘.format(321.3456)out[9]: ‘321.34‘

其中.2表示長度為2的精度,f表示float類型。

其他類型

主要就是進位, b, d, o, x分別是二進位、十進位、八進位和十六進位

In[10]: ‘{:b}‘.format(17)out[10]: ‘10001‘In[11]: ‘{:d}‘.format(17)out[11]: ‘17‘In[12]: ‘{:o}‘.format(17)out[12]: ‘21‘

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

In[13]: ‘{:,}‘.format(1234567890)out[13]: ‘1,234,567,890‘

 

Python 的格式化字串format函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.