python2和3print的区别-Python教程

资源魔 42 0

正在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的区分的具体内容,更多请存眷资源魔其它相干文章!

标签: print python教程 python编程 python使用问题

抱歉,评论功能暂时关闭!