Python 2与Python 3中print语句与函数的核心差异解析
本文对比分析Python 2与Python 3中print机制的根本差异。Python 2中print为语法结构,无需括号且默认换行;Python 3中print为内置函数,必须使用括号,支持sep、end、file等参数。文章详细讲解了多参数打印、自定义分隔符、不换行输出及文件重定向的实现方式,并介绍了如何在Python 2中通过__future__模块兼容Python 3的print行为。
在Python 2和Python 3中,print()都用于输出信息,但两个版本对print的处理机制存在显著差异。
这些差异主要体现在以下几个关键方面:
首先,在Python 3中,print是一个内置函数,拥有多个参数;而在Python 2中,print是一个语法结构(语句)。
其次,在Python 2中打印字符串时可以省略括号,例如print 'hello world';而在Python 3中必须使用括号,即print("hello world")。
此外,在Python 2中,input()函数要求输入的字符串必须加引号,为了避免读取非字符串类型时发生的一些意外行为,开发者通常不得不使用raw_input()来代替input()。
在Python 3中,开发者可能认为print同时具备语法结构和函数两种身份会造成混淆,因此只保留了其作为函数的身份。
其函数原型为:print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)。
从上述方法原型中可以看出:
第一,print支持多个参数,可以同时打印多个字符串(其中...表示任意数量的参数)。
第二,sep参数用于指定多个字符串之间的连接字符。
第三,end参数用于指定字符串结尾添加的字符。通过设置该参数,可以轻松实现打印不换行。在Python 2.x中,print语句输出字符串后默认换行,若不希望换行,只需在语句末尾加一个逗号即可。但在Python 3.x中,由于print()变为内置函数,这种加逗号的老方法不再适用。
>>> print("python", "tab", ".com", sep='')
pythontab.com
>>> print("python", "tab", ".com", sep='', end='') #就可以实现打印出来不换行
pythontab.com
Python 2中打印时可以不加括号,例如print 'hello world';而Python 3中必须加括号,例如print("hello world")。
在Python 3中,print必须使用括号,因为它的本质就是一个函数。
总体而言,Python 2.7中的print不是一个函数,而Python 3中的print是一个函数。两者调用方式的主要区别如下:
print 'this is a string' #python2.7
print('this is a string') #python3
当然,在Python 2.7中也可以使用括号将变量括起来,这样操作完全正确:
print('this is a string') #python2.7
但是,Python 3将print改为函数并非毫无意义:
第一,在Python 3中,可以使用help(print)查看其文档,而在Python 2中无法做到这一点:
>>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.
第二,在Python 3中,可以更便捷地使用输出重定向功能。
在Python 2.7中,你需要采用类似C++的风格来完成重定向操作:
with open('print.txt', 'w') as f:
print >> f, 'hello, python!'
而在Python 3中,实现方式如下:
with open('print.txt', 'w') as f:
print('hello, python!', file = f)
file是Python 3中print新增的一个参数。另一个非常实用的参数是sep,例如打印一个整数数组,但你想用星号而不是空格连接。在Python 2中可能需要编写一个循环来完成,而在Python 3中只需这样写即可:
a = [1, 2, 3, 4, 5] print(*a, sep = '*')
最后,如果想在Python 2.7中使用Python 3风格的print,只需在代码第一行加入:
from __future__ import print_function
需要注意的是,from __future__ import ...这类语句必须放置在代码文件的开头处。
关于print输出的差异,同一段代码在不同版本中的表现如下:
#/usr/bin/env python
#coding:utf-8
for i in range(1,10):
for j in range(1,10):
for k in range(1,10):
if(i != k)and(i != j)and(k != j):
print(i,j,k)
Python 2的输出结果为 i,j,k(带有逗号)。Python 3的输出结果为 i j k(空格分隔)。Python 3的输出直接屏蔽了逗号,仅保留空格。
另外,Python 2的print后续可不添加括号;而Python 3必须添加括号。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









