首先明确一点,input()与raw_input()的区别只存在Python2.X环境下,因为在Python3中将Python2中的input()删除了,同时将raw_input()改名为input()。
如果你主要使用Py3,那么你只需关注在使用input()时所输入的数据最后都会输出成字符串格式,所以当你进行数字格式输入时要利用int()做好格式转换。
Py2.x环境下运行:
# 例1
>>> a = input("Please input your age: ")
Please input your age: 18
>>> a
18
# 例2
>>> a = input("Please input your name: ")
Please input your name: jason
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'virgin' is not defined
通过例1与例2做对比,我们可以发现在Py2环境下使用input()函数输入字符串的话,必须严格按照以引号方式输入字符串,如下所示:
# 例3
>>> a = input("Please input your name: ")
Please input your name: "jason"
>>> a.title()
Jason
# 例4
>>> a = raw_input("Please input your name: ")
Please input your name: jason
>>> a.title()
'Jason'
>>> a = raw_input("Please input your age: ")
Please input your favorite number: 18
>>> a
'18'
通过例4我们可以直观地看到,在Py2环境下raw_input()函数会将所有输入的数据一律都转换为字符串格式.
结论:
如果想要在Py2环境下使用input()函数输入字符串的话,必须严格按照以引号方式输入字符串.当然更便捷的方法,尽量多使用raw_input()而避免使用input().很显然Py3环境下并不存在这个问题,因为只有input()可供使用.