新浪博客

Python中print()常用输出方法

2018-05-15 15:28阅读:
print函数用法
1. 输出字符串
print 'Hello World'
print 'Hello World'
print ('Hello World')
print ('Hello World')
[注] 对于Python 3.0及以上版本,print是函数,因此需要编写print ()而不是print。
输出结果:
Hello World
Hello World
Hello World
Hello World
2. 格式化输出整数
print 'The length of \'%s\' is %d.' %('Hello World',len('Hello World'))
输出结果:
The length of 'Hello World' is 11.
3. 格式化输出十六进制、十进制、八进制整数
%x —————— hex 十六进制
%d —————— dec 十进制
%o —————— oct 八进制
a = 0xFF
print 'hex=%x,dec=%d,oct=%o' %(a,a,a)
输出结果:

hex=ff,dec=255,oct=377
-----------------------------------------------------------------------
4. 格式化输出浮点数
%f —————— 输出浮点数
%.3f —————— 保留三位小数输出浮点数
%6.3f —————— 包含小数点共六位,小数点后保留三位输出浮点数
.3f —————— 包含小数点共六位,小数点后保留三位,不足补零输出浮点数

import math
print 'PI=%f' %math.pi
print 'PI=%.3f' %math.pi
print 'PI=%6.3f' %math.pi
print 'PI=%-6.3f' %math.pi
print 'PI=.3f' %math.pi

输出结果:
PI=3.141593
PI=3.142
PI= 3.142
PI=3.142
PI=03.142

5. 格式化输出字符串
%s —————— 输出字符串
print '%s'%'Today is Tuesday'
输出结果:
Today is Tuesday

6. 输出列表及字典
列表:
a=[1, 0xFA, 5, 'Python']
print a
输出结果:
[1, 250, 5, 'Python']

输出字典:
a={'name':'Jack', 'gender':'Male', 'age':25, 'city':'London'}
print a
输出结果:
{'gender': 'Male', 'age': 25, 'name': 'Jack', 'city': 'London'}

我的更多文章

下载客户端阅读体验更佳

APP专享