对于任何一门编程语言,第一个入门例子肯定是输出hello world。在C语言中使用printf()函数打印字符串,而在python2中使用print即可,之所以强调是python2,是因为python2版本和3版本有所差异且没有向上兼容。
python2中的print
在python2中print是一个标准的输出语句。在输出字符串时,可以带括号,也可以不带。
Python 2.7.5 (default, Apr 2 2020, 13:16:51)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'Hello World' #不带括号
Hello World
>>> print('Hello World') #带括号
Hello World
使用help(‘print’)输出如下图:
python3中的print
在python3中print升级为了一个函数,print()函数一次可以打印多个对象,打印的对象可以是任意类型,print()函数有4个默认参数。
- sep:值之间插入的字符串,默认为空格
- end:在最后一个值后面附加的字符串,默认为换行
- file:一个类似文件的对象(流),默认为当前的sys.stdout(标准输出控制台)
- flush:是否立即输出缓存,默认不会被输出
Python 3.6.2 (default, Mar 1 2021, 16:00:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 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.
一次可以打印多个对象,对象可以是任意类型
>>> print(1,[1,2],{'user':'Andy'})
1 [1, 2] {'user': 'Andy'}
打印多个对象,使用#分隔
>>> print(1,'x',2,'y',sep='#')
1#x#2#y
不换行打印
>>> for i in range(4):
... print(i, end=' ')
...
0 1 2 3
将打印内容输出到文件
>>> with open('./print_out.txt','w') as f:
... print('I am Andy!',file=f)
...
>>>exit()
[root@yace ~]# cat print_out.txt
I am Andy!
使用print()函数实现打印机效果
# -*- coding: utf-8 -*-
import time
def printer(text, delay=0.3):
for ch in text:
print(ch, end='', flush=True)
time.sleep(delay)
print()
if __name__ == '__main__':
printer('少年不识愁滋味,爱上层楼。爱上层楼,为赋新词强说愁。\n而今识尽愁滋味,欲说还休。欲说还休,却道天凉好个秋。')
打印机输出效果如下: