python2.x中input跟raw_input的區別

對於標準輸入的處理,不同於py3,將所有標準輸入均處理爲字符串,py2中則嚴格區分數值跟字符串。

py3:
print(type(input()))
>>12
12
<class 'str'>

py2:
print(type(input()))
>>12
12
<type 'int'>

但是對於py2 input字符串去有所不同:

print(type(input()))
>>asd
Traceback (most recent call last):
  File "c:\Users\Stan Pao\Desktop\辦公\Python\Test\new.py", line 1, in <module>
    print(type(input()))
  File "<string>", line 1, in <module>
NameError: name 'asd' is not defined
------------------------------------
py2中的input在輸入字符串時需要嚴格用引號標識出字符串
print(type(input()))
>>‘asd’
'asd'
<type 'str'>

鑑於py2中input()對輸入數據類型嚴格的區分,因此多使用raw_input(),作用同py3中input,全作爲字符串輸入。

print(type(raw_input()))
12
<type 'str'>
asdf
<type 'str'>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章