1. 程式人生 > >python 字符串格式化輸出 %d,%s及 format函數

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

浮點數 nbsp align p s pos () 關鍵字參數 pri blog

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

總結:

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

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