Python2、Python3中print的不同点解析
内容摘要
这篇文章主要为大家详细介绍了Python2、Python3中print的不同点解析,具有一定的参考价值,可以用来参考一下。
对python这个高级语言对此感兴趣的朋友,看看idc笔记做的技术笔记
对python这个高级语言对此感兴趣的朋友,看看idc笔记做的技术笔记
文章正文
这篇文章主要为大家详细介绍了Python2、Python3中print的不同点解析,具有一定的参考价值,可以用来参考一下。
对python这个高级语言对此感兴趣的朋友,看看idc笔记做的技术笔记!在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同时具有两重身份有些不爽,就只留了其中函数的身份:
1 2 3 4 5 6 | <code class = "bash" > >>> print '512pic.com' SyntaxError: Missing parentheses in call to 'print' # End www_512pic_com </code> |
所以python3中print必须使用括号,因为它就是一个函数。
2. python3中print函数有多个参数,函数原型如下:
1 2 3 4 5 | <code class = "bash" > print (value1, ..., sep= ' ' , end = '\n' , file=sys.stdout, flush =False) # End www_512pic_com </code> |
从上面的方法原型可以看出,
1. print可以支持多个参数,支持同时打印多个字符串(其中...表示任意多个字符串);
2. sep表示多个字符串之间使用什么字符连接;
3. end表示字符串结尾添加什么字符,指点该参数就可以轻松设置打印不换行,Python2.x下的print语句在输出字符串之后会默认换行,如果不希望换行,只要在语句最后加一个“,”即可。但是在Python 3.x下,print()变成内置函数,加“,”的老方法就行不通了。
1 2 3 4 5 6 7 8 9 | <code class = "bash" > >>> print ( "python" , "tab" , ".com" , sep= '' ) 512pic.com >>> print ( "python" , "tab" , ".com" , sep= '' , end = '' ) #就可以实现打印出来不换行 512pic.com # End www_512pic_com </code> |
3.Python2中input的坑
1 2 3 4 5 6 7 | <code class = "bash" > print ( "what do you like" ) a = input( "Enter any content:" ) print ( "i like" ,a) # End www_512pic_com </code> |
输入字符串时会报错,而在python3中很好地解决了这个问题。
注:关于Python2、Python3中print的不同点解析的内容就先介绍到这里,更多相关文章的可以留意
代码注释