Python2和Python3中print的不同点

发布时间:2021-11-25 09:51:26 人气:263 作者:多测师

Python2和Python3中print的不同点

  在Python2和Python3中都提供print()方法来打印信息,但两个版本间的print稍微有差异

  主要体现在以下几个方面:

  1.python3中print是一个内置函数,有多个参数,而python2中print是一个语法结构;

  2.Python2打印时可以不加括号:print 'hello world', Python3则需要加括号 print("hello world")

  3.Python2中,input要求输入的字符串必须要加引号,为了避免读取非字符串类型发生的一些行为,不得不使用raw_input()代替input()

  一. python3中,或许开发者觉得print同时具有两重身份有些不爽,就只留了其中函数的身份:

  >>> print 'pythontab.com'

  SyntaxError: Missing parentheses in call to 'print'

  所以python3中print必须使用括号,因为它就是一个函数。

Python2和Python3中print的不同点

  二. python3中print函数有多个参数,函数原型如下:

  print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

  从上面的方法原型可以看出,

  (1). print可以支持多个参数,支持同时打印多个字符串(其中...表示任意多个字符串);

  (2). sep表示多个字符串之间使用什么字符连接;

  (3). end表示字符串结尾添加什么字符,指点该参数就可以轻松设置打印不换行,Python2.x下的print语句在输出字符串之后会默认换行,如果不希望换行,只要在语句最后加一个“,”即可。但是在Python 3.x下,print()变成内置函数,加“,”的老方法就行不通了。

  >>> print("python", "tab", ".com", sep='')

  pythontab.com

  >>> print("python", "tab", ".com", sep='', end='') #就可以实现打印出来不换行

  pythontab.com

  三.Python2中input的坑

  print ("what do you like")

  a = input("Enter any content:")

  print ("i like",a)

  输入字符串时会报错,而在python3中很好地解决了这个问题。

  以上内容为大家介绍了Python2和Python3中print的不同点,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/

返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线