python 字串格式化輸出 %d,%s及 format函數

來源:互聯網
上載者:User

標籤:ext   轉換   math   函數   bsp   方式   pytho   浮點   一個   

舊式格式化方式:%s,%d

1、順序填入格式化內容

s = "hello %s, hello %d"%("world", 100)print(s)

結果: ‘hello world, hello 100‘

2、使用關鍵字參數

s= "%(name)s age %(age)d"%{"name":"Tom", "age":10}
print(s)

結果:Tom name 10

常用的格式化符號

%s 對應的是字串類型(str)
%d 對應十進位整數型的(int)

%f  對應浮點數(float)

 %r 對應字串(repr)

利用format()函數

1、無參數情況

s = "hello {}, hello {}".format("world","Python")print(s)

結果:"hello world, hello Python"

2、位置參數

s = "hello {1}, hello {0}".format("world","Python")print(s)

結果:"hello Python, hello world"

3、關鍵詞參數

s = "hello {first}, hello{second}".format(first="world",second="Python")print(s)

結果: "hello world, hello Python"

4、位置參數與關鍵詞參數混用

       位置參數放在關鍵詞參數前面,否則報錯

s = "hello {first}, hello{0}".format(Python, first="world")print(s)

結果:"hello world, hello Python"

5、"!a"(運用ascii()), "!s"(運用str()),  "!r"(運用repr())可以在格式化之前轉換相應的值。

In [21]: contents = "eels"In [22]: print("My hovercraft is full if {}.".format(contents))My hovercraft is full if eels.In [23]: print("My hovercraft is full if {!r}.".format(contents))My hovercraft is full if ‘eels‘.In [24]: print("My hovercraft is full if {!s}.".format(contents))My hovercraft is full if eels.In [25]: print("My hovercraft is full if {!a}.".format(contents))My hovercraft is full if ‘eels‘.

6、欄位後可以用":"和格式指令,更好的控制格式。

    (1)、下段代碼將π 近似到小數點後3位

import mathprint("The value of PI is approximately {0:.3f}.".format(math.pi))

結果:3.142

   (2)、":"後面緊跟一個整數可以限定該欄位的最小寬度

table = {‘Sjoerd‘: 4127, ‘Jack‘: 4098, ‘Dcab‘: 7678}for name, phone in table.items():     print(‘{0:10} ==> {1:10d}‘.format(name, phone))

結果:

Jack       ==>       4098Dcab       ==>       7678Sjoerd     ==>       4127
總結:

%格式化為python內建的操作符,常用的為本文提到的這幾個,還有一些其他的,如進位相關的,想瞭解可以尋找其他資料。format是利用Python內建函數,關於format還有更多的用法,如格式限定,精度確定,填充與對齊等。

 

python 字串格式化輸出 %d,%s及 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.