python基础之print函数

对于任何一门编程语言,第一个入门例子肯定是输出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而今识尽愁滋味,欲说还休。欲说还休,却道天凉好个秋。')

打印机输出效果如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值