Python print formatted output

Python print formatted output

1. Formatted output integer
python print also supports parameter formatting, similar to printf in C language,

strHello = "the length of (%s) is %d" %(Hello World,len(Hello World))
print strHello
#output Result: the length of (Hello World) is 11


2. Formatted output 16-system integer
nHex = 0x20
#%x --- hex hexadecimal
#%d --- dec decimal
#%d --- oct octal
 
print "nHex = %x, nDec = %d, nOct = %o" %(nHex,nHex,nHex)
 
#Output result: nHex = 20,nDec = 32,nOct = 40 #Print
the same number using each system of integers


3. Format the output floating point number (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 #Fill
characters in front
print "PI = d" % int(math.pi) #Output
 
result
#PI = 3.141593
#PI = 3.142
#PI = 3.142
#PI = 000003 #Format
of floating-point numbers, precision


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 = {1:A,2:B,3:C,4:D}
print d
#输出结果:{1: A, 2: B, 3: C, 4: D}
#同python也是支持dictionary出的


7.python print自动换行
print 会自动在行末加上回车,如果不需回车,只需在print语句的结尾添加一个逗号",",就可以改变它的行为。

for i in range(0,5):
    print i,
或直接使用下面的函数进行输出:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325924157&siteId=291194637