Python標準庫:內建函數format(value[, format_spec]),pythonformat_spec

來源:互聯網
上載者:User

Python標準庫:內建函數format(value[, format_spec]),pythonformat_spec

本函數把值value按format_spec的格式來格式化,然而函數解釋format_spec是根據value的類型來決定的,不同的類型有不同的格式化解釋。當參數format_spec為空白時,本函數等同於函數str(value)的方式。

其實本函數調用時,是把format(value, format_spec)的方式轉換為type(value).__format__(format_spec)方式來調用,因此在value類型裡就尋找方法__format__(),如果找不到此方法,就會返回異常TypeError。

其中format_spec的編寫方式如下形式:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]

fill        ::=  <any character>

align       ::=  "<" | ">" | "=" | "^"

sign        ::=  "+" | "-" | " "

width       ::=  integer

precision   ::=  integer

type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

fill是表示可以填寫任何字元。

align是對齊,<是靠左對齊, >是靠右對齊,^是置中對齊。

sign是符號, +表示正號, -表示負號。

width是數字寬度,表示總共輸出多少位元字。

precision是小數保留位元。

type是輸出數字值是的表示方式,比如b是二進位表示;比如E是指數表示;比如X是十六進位表示。

例子:

#format()print(format(2918))print(format(0x500, 'X'))print(format(3.14, '0=10'))print(format(3.14159, '05.3'))print(format(3.14159, 'E'))print(format('test', '<20'))print(format('test', '>20'))print(format('test', '^20'))

結果輸出如下:

2918

500

0000003.14

03.14

3.141590E+00

test                

                test

        test        

 


蔡軍生  QQ:9073204 深圳

聯繫我們

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