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


舊式格式化方式:%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)

3、輸出百分數

"%.2f%%"%(0.123)
# = 0.12%

 

 

利用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 math
print("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       ==>       4098
Dcab       ==>       7678
Sjoerd     ==>       4127

(3)、數字加千分位符

print("{0:,.2f}".format(12345678.12345))
# 輸出 12,345,678.12

注意:使用format輸出最終都為字符串類型

總結:

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM