Python print格式化輸出

2021-08-06 07:24:58 字數 1596 閱讀 8094

python print格式化輸出

1.格式化輸出整數

python print也支援引數格式化,與c言的printf似,

strhello = "the length of (%s) is %d" %(hello world,len(hello world))

print strhello

#輸出果:the length of (hello world) is 11

2.格式化輸出16制整數

nhex = 0x20

#%x --- hex 十六進製制

#%d --- dec 十進位制

#%d --- oct 八進位制

print "nhex = %x,ndec = %d,noct = %o" %(nhex,nhex,nhex)

#輸出結果:nhex = 20,ndec = 32,noct = 40

#使用整數的各個制列印同乙個數

3.格式化輸出浮點數(float)

import math

#default

print "pi = %f" % math.pi

#width = 10,precise = 3,align = left

print "pi = .3f" % math.pi

#width = 10,precise = 3,align = rigth

print "pi = %-10.3f" % math.pi

#前面填充字元

print "pi = d" % int(math.pi)

#輸出結果

#pi = 3.141593

#pi =      3.142

#pi = 3.142

#pi = 000003

#浮點數的格式化,精度

4.格式化輸出字串(string)

#precise = 3

print "%.3s " % ("jcodeer")

#precise = 4

print "%.*s" % (4,"jcodeer")

#width = 10,precise = 3

print ".3s" % ("jcodeer")

#輸出結果:

#jco

#jcod

#       jco

#同於字串也存在精度、度和。

5.輸出列表(list)

l = [1,2,3,4,jcodeer]

print l

#輸出結果:[1, 2, 3, 4, jcodeer]

#於list直接列印即可

6.輸出字典(dictionary)

d =

print d

#輸出結果:

#同python也是支援dictionary出的

7.python print自動換行

print 會自動在行末加上回車,如果不需回車,只需在print語句的結尾新增乙個逗號",",就可以改變它的行為。

for i in range(0,5):

print i,

或直接使用下面的函式進行輸出:

sys.stdout.write("輸出的字串")

python print函式格式化輸出

1 club.topsage.com python print函式用法,print 格式化輸出 使用print輸出各型的 1.字串 2.整數 3.浮點數 4.出度及精度控制 strhello hello python print strhello 輸出結果 hello python 直接出字串 1....

基礎教程 Python格式化字串(格式化輸出)

print 函式使用以 開頭的轉換說明符對各種型別的資料進行格式化輸出,具體請看下表。表 1 python 轉換說明符 轉換說明符 解釋 d i 轉換為帶符號的十進位制整數 o轉換為帶符號的八進位制整數 x x 轉換為帶符號的十六進製制整數 e轉化為科學計數法表示的浮點數 e 小寫 e轉化為科學計數...

格式化,強調 數值格式化

聚合函式返回的的數值型別的值有個特點就是沒有被格式化。通過前面的帶 sum 聚合函式的示例,我們可以看到這一點 注意合計值 命令,或者在物件檢視器中選中 displayformat 屬性。在上節的示例中,格式化操作是針對一物件或物件內的表示式,在物件內僅有乙個表示式時它還能正常工作,不過當物件內不有...