知行编程网知行编程网  2022-11-16 08:30 知行编程网 隐藏边栏  1 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python3与2中print有什么区别?的相关知识,包括python2和python3主要有哪些不同,以及python中的if这些编程知识,希望对大家有参考作用。

区别:Python2中的print是一个关键字,而Python3中的print是一个函数。关键字用法“打印要打印的内容”;函数用法“打印(打印什么)”。

python3和2中的print有什么区别?

总地来说, Python2.7的print不是一个function,而Python3里的print是一个function。

两都调用方式的主要区别如下:

print 'this is a string' #python2.7
print('this is a string') #python3

当然,在python2.7中也可以用括号括起来变量,完全没有错:

print('this is a string') #python2.7

但是python3将print改成function不是白给的:



1. 在python3里,能使用help(print)查看它的文档了, 而python2不行:

>>help(print)
Help on built-in function print in module builtins:

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.



2 . 在python3里,能更方便的使用输出重定向



python2.7里,你需要以类似于C++的风格完成重定向:

with open('print.txt', 'w') as f:
    print >> f, 'hello, python!'

在python3里:

with open('print.txt', 'w') as f:
    print('hello, python!', file = f)

file是python3 print新增的参数。另一个方便的参数是 sep,例如打印一个整数数组,但你想用星号而不是空格连接。在python2中,可能需要写一个循环来完成。在 python3 中,这将执行:

a = [1, 2, 3, 4, 5]
print(*a, sep = '*')

最后,如果要在python2.7中使用python3的print,只要在第一段代码前加上即可:

from __future__ import print_function

注意, from __future__ import ...一类的语句一定要放在代码开始处。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享