Python 3 进阶 —— print 打印和输出
2018-07-20 18:33
351 查看
在 Python 中,
在 2.x 版本中,
参数选项
可以用
help(print)来查看
print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
- value: 打印的值,可多个
- file: 输出流,默认是
sys.stdout
- sep: 多个值之间的分隔符
- end: 结束符,默认是换行符
\n
- flush: 是否强制刷新到输出流,默认否
能打印任意数据
- 打印数字、字符串、布尔值
print(1024, 10.24, 'hello', False) # 1024 10.24 hello False
- 打印列表
print([1, 2, 3]) # [1, 2, 3]
- 打印元组
print((1, 2, 3)) # (1, 2, 3)
- 打印字典
print({'name': 'hello', 'age': 18}) # {'name': 'hello', 'age': 18}
- 打印集合
print({1, 2, 3}) # {1, 2, 3}
- 打印对象
class Demo: pass demo = Demo() print(demo) # <__main__.Demo object at 0x1005bae80>
分隔符
默认分隔符是空格,
sep参数可以修改。
print(1, 2, 3, sep='-') # 1-2-3
结束符
默认结束符是行号,
end参数可以修改。
print('第一行', end='-') print('第二行') # 第一行-第二行
输出重定向
默认情况下,
with open('data.log', 'w') as fileObj: print('hello world!', file=fileObj)
此时,不会有任何标准输出,但对应的文件中已经有了内容。
我们也可以输出到错误输出流,例如:
import sys print('hello world!', file=sys.stderr)
参考资料
相关文章推荐
- [第一章]在Python中如何让两个print()函数的输出打印在一行内?
- Python print 输出打印不换行
- python print 打印unicode string的时候 去掉u' remove u'
- Python print 不换行打印
- python打印即时输出的方法
- Python print 输出到文件(open)
- 【Python】python多进程,函数内print的内容没有打印出来
- Python的Print打印中文乱码解决方案
- python2.7 print不换行输出
- [置顶] 【python pandas】 Dataframe的数据print输出 显示为...省略号
- python学习002-Python print 输出不换行
- python 的print输出
- python学习之print输出不换行
- python print输出到文件
- 菜鸟学Python之一:使用print输出信息
- python的输出 print print, write
- python print如何不换行输出
- Python3基础 在print中用 %d 输出一个整数
- PHP打印输出数组内容及结构函数print_r与var_dump
- Python +Selenium logging模块打印日志并输出到记事本中