美文网首页
2018-02-24python2、3 print详解

2018-02-24python2、3 print详解

作者: QA_man | 来源:发表于2018-02-24 10:53 被阅读0次

python 2 print 语句:

只能是逗号作为分隔符、只能是逗号结尾能去除换行符

  1. print 'a'这是一个语句,不是一个函数
  2. 实现方式:
print A 相当于执行sys.stdout.write(str(A)+'\n')
print A,B,C 相当于执行了sys.stdout.write(' '.join(map(str,[A,B,C]))+'\n')
print A, 相当于执行了sys.stdout.write(str(A))没有末尾的换行符

重定向输出存储从 2.0版本开始,Python引入了print >>的语法,作用是重定向print语句最终输出字符串的文件。例如,print >> output(output 是文件对象), A相当于output.write(str(A) + '\n')。

python3 print 函数

可以指定分隔符(separator)、结束符(endstring)、自定义print函数

变成函数之后,print就可以组件化了,作为语句的print是无法支持的,你还可以编写自己喜欢的print函数,将其赋值给builtins.print,就可以覆盖掉自带的函数实现了。这一点在Python 2中是不可能实现的。

如果用Python来实现print函数,它的函数定义应该是这样的:

import sys
sep :设置分隔符默认是空格
end :  设置结束字符串,默认是换行符
file : 存储文件,默认打印在consol

def print(*objects, sep=None, end=None, file=None, flush=False):
    """A Python translation of the C code for builtins.print()."""
    if sep is None:
        sep = ' '
    if end is None:
        end = '\n'
    if file is None:
        file = sys.stdout
    file.write(sep.join(map(str, objects)) + end)
#map(str,"abc")使用str函数去循环比哪里出 abc 字符列表
    if flush:
        file.flush()
从上面的代码中,我们可以发现:Python 3中的print函数实现了print语句的所有特性。

print A == print(A)
print A, B, C == print(A, B, C)
print A, == print(A, end='')
print >> output, A == print(A, file=output)
从上面的示例代码中我们就可以看出,使用print函数有明显的好处:与使用print语句相比,
我们现在能够指定其他的分隔符(separator)和结束符(endstring)。

相关文章

网友评论

      本文标题:2018-02-24python2、3 print详解

      本文链接:https://www.haomeiwen.com/subject/sdcqxftx.html