在python中raw_input()和input()都是提示并获取用户输入的函数,然后将用户的输入数据存入变量中。但二者在处理返回数据类型上有差别。
input()函数是raw_intput()和eval()函数的功能的组合即:input()=eval(raw_input()),eval对用户输入的数据进行了求值,并返回求值结果。
raw_input()函数输入任何类型的数据都会被存储为一个字符串。
str类型-->str:
1 >>> s=raw_input("raw here:") 2 raw here:Tom ok! 3 >>> type(s) 4 <type 'str'> 5 >>> print s 6 Tom ok!
int类型-->str:
1 >>> s=raw_input("raw here:") 2 raw here:66 3 >>> type(s) 4 <type 'str'>
list类型-->str:
1 >>> s=raw_input("raw here:") 2 raw here:[1,2,3] 3 >>> type(s) 4 <type 'str'>
input()函数不改变输入数据的类型。
str类型-->str
1 >>> s=input("input here:") 2 input here:"Tom ok!" 3 >>> type(s) 4 <type 'str'> 5 >>> print s 6 Tom ok!
int类型-->int:
1 >>> s=input("input here:") 2 input here:55 3 >>> type(s) 4 <type 'int'>
list类型-->list:
1 >>> s=input("input here:") 2 input here:[1,2,3] 3 >>> type(s) 4 <type 'list'>
raw_input()函数输入任何类型的数据都会被视为一个字符串,且在输入字符串时不需要加引号。
1 >> s=raw_input("input your name:") 2 input your name:bell 3 >>> print s 4 bell
input()函数直接接受且不改变输入数据的类型,但是需要注意的是使用input()在输入字符串时需要添加引号,否则会报错。
不添加引号报错:
1 >>> s=input("input here:") 2 input here:hello 3 Traceback (most recent call last): 4 File "<stdin>", line 1, in <module> 5 File "<string>", line 1, in <module> 6 NameError: name 'hello' is not defined
添加引号正常:
1 >>> s=input("input here:") 2 input here:"hello" 3 >>>
本文详细解析了Python中input()与raw_input()函数的区别,包括它们如何处理不同类型的输入数据,以及使用这些函数时应注意的事项。
1217

被折叠的 条评论
为什么被折叠?



