目录
0 导语
咳咳,此文是专门写给新手们(包括我)的一片好(shui)文,大佬们可以右上角了
所有学python的童鞋们都会从这句话开始:
print "Hello World!"
或是
print("Hello World!")
python的 print 分为两个版本,分别是2.*的关键字版本和3.*的函数版本
1 python2.*版
1.1 关键字print
如果你的python版本为2.*,print 则是个关键字:
>>> print 1
1
>>> print "abc"
abc
这时2.1以上的版本可以使用 __future__ 模块导入 python3.*版本的 print 函数
>>> print 1
1
>>> from __future__ import print_function
>>> print(1, 1)
1 1
1.2 __future__
关于 __future__ 的作用,官方文档中也有明确提到:
__future__ is a real module, and serves three purposes:
1. To avoid confusing existing tools that analyze import statements and expect to find the modules they’re importing.
2. To ensure that future statements run under releases prior to 2.1 at least yield runtime exceptions (the import of __future__ will fail, because there was no module of that name prior to 2.1).
3. To document when incompatible changes were introduced, and when they will be — or were — made mandatory. This is a form of executable documentation, and can be inspected programmatically via importing __future__ and examining its contents.
总结三个字:兼容性
咳咳,扯远了
2 python3.*版本
2.1 名参
python最新版 print 函数的关键字参数有四个:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
value, ...:要打印的值
sep:即在值之间插入的字符串,默认为空格,默认为' '(一个空格)
end:即为最后一个值后附加的值,默认为'\n'(换行)
file:默认值为sys.stdout,代表系统标准输出。我们可以通过改变该参数使print()函数输出到特定的文件中
flush:用于控制输出缓存,如果输出需要刷新则调整为True
2.2 DEMO
最后再来一个demo:
#demo.py
from time import sleep
print("__bai__", "s first work", sep="'", end=" is here", flush=True)
for i in range(20):
sleep(0.2)
print("~", end="")