# python3.2中print函数用法实例详解

1. 输出字符串

>>> strhello = ‘hello world’
>>> print (strhello)
hello world

2. 格式化输出整数

>>> strhello = “the length of (%s) is %d” %(‘hello world’,len(‘hello world’))
>>> print (strhello)
the length of (hello world) is 11

3. 格式化输出16进制，十进制，八进制整数

#%x — hex 十六进制
#%d — dec 十进制
#%o — oct 八进制

>>> nhex = 0xff
>>> print(“nhex = %x,ndec = %d,noct = %o” %(nhex,nhex,nhex))
nhex = ff,ndec = 255,noct = 377

4.格式化输出浮点数(float)

import math
>>> print(‘pi=%f’%math.pi)
pi=3.141593
>>> print (“pi = %10.3f” % math.pi)
pi = 3.142
>>> print (“pi = %-10.3f” % math.pi)
pi = 3.142
>>> print (“pi = %06d” % int(math.pi))
pi = 000003

5. 格式化输出浮点数(float)

>>> precise = 3
>>> print (“%.3s ” % (“python”))
pyt
>>> precise = 4
>>> print (“%.*s” % (4,”python”))
pyth
>>> print (“%10.3s ” % (“python”))
pyt

6.输出列表(list)

>>> lst = [1,2,3,4,’python’]
>>> print (lst)
[1, 2, 3, 4, ‘python’]

>>> d = {1:’a’,2:’b’,3:’c’,4:’d’}
>>> print(d)
{1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’}

7. 自动换行

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

>>> for i in range(0,6):
print (i,)
0
1
2
3
4
5

>>> import sys
>>> sys.stdout.write(‘hello world’)
hello world