Python之格式化輸出講解

2022-03-21 05:59:00 字數 1554 閱讀 3593

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之格式化輸出

1 整數的輸出 o oct 八進位制 d dec 十進位制 x hex 十六進製制 2 浮點數輸出 1 格式化輸出 f 保留小數點後面六位有效數字 3f,保留3位小數字 e 保留小數點後面六位有效數字,指數形式輸出 3e,保留3位小數字,使用科學計數法 g 在保證六位有效數字的前提下,使用小數方式,...

Python格式化輸出之pprint

簡介 pprint模組提供了列印出python資料結構類和方法。模組方法 建立乙個prettyprinter物件 indent 縮排,width 一行最大寬度,depth 列印的深度,這個主要是針對一些可遞迴的物件,如果超出指定depth,其餘的用 代替。eg a 1,2,3,4,5 a的深度就是2...

Python基礎之格式化輸出

python中用 代 式符,或者叫佔位符 表示格式化操作,將其轉化成相應的資料型別 age 10print 我今年 d歲 age 我今年10歲在程式中,看到了 這樣的操作符,這就是python格式化輸出 age 19name xiaoming print 我的名字是 s,年齡是 d歲 name,ag...