在Python2和Python3中都供应print()要领来打印信息,但两个版本间的print轻微有差别
重要体现在以下几个方面:
1.python3中print是一个内置函数,有多个参数,而python2中print是一个语法结构;
2.Python2打印时能够不加括号:print 'hello world', Python3则需要加括号 print("hello world")
3.Python2中,input请求输入的字符串必需要加引号,为了防止读取非字符串范例发作的一些行动,不能不运用raw_input()替代input()
1. python3中,也许开发者以为print同时具有两重身份有些不爽,就只留了个中函数的身份:
print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
从上面的要领原型能够看出,
①. print能够支撑多个参数,支撑同时打印多个字符串(个中...示意恣意多个字符串);
②. sep示意多个字符串之间运用什么字符衔接;
③. end示意字符串末端增加什么字符,指导该参数就能够轻松设置打印不换行,Python2.x下的print语句在输出字符串之后会默许换行,假如不愿望换行,只要在语句末了加一个“,”即可。然则在Python 3.x下,print()变成内置函数,加“,”的老要领就行不通了。
>>> print("python", "tab", ".com", sep='') pythontab.com >>> print("python", "tab", ".com", sep='', end='') #就能够完成打印出来不换行 pythontab.com
固然,python2.7里你也能够用括号把变量括起来, 一点都不会错:
print('this is a string') #python2.7
然则python3将print改成function不是白给的:
在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.
在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新加的一个参数。 另一个很handy的参数是sep, 比方打印一个整数数组, 但你想用星号而不是空格衔接。python2时能够需要写一个轮回来完成, python3里如许就好了:
a = [1, 2, 3, 4, 5] print(*a, sep = '*')<br>
末了, 假如想在python2.7里运用python3的print,只需要在第一句代码前到场:
from __future__ import print_function
注重, from __future__ import ...一类的语句一定要放在代码最先处。
以上就是python2和3print的区分的细致内容,更多请关注ki4网别的相干文章!