python3.x中的raw_input()
和input()
有什麼區別? python
raw_input()
徹底接受用戶鍵入的內容,並將其做爲字符串傳遞迴。 shell
input()
首先使用raw_input()
,而後對其執行eval()
。 python3.x
主要區別在於input()
須要語法正確的python語句,而raw_input()
則不須要。 安全
raw_input()
重命名爲input()
所以如今input()
返回確切的字符串。 input()
已刪除。 若是要使用舊的input()
,這意味着須要將用戶輸入評估爲python語句,則必須使用eval(input())
手動進行操做。 函數
我想在每一個人爲python 2用戶提供的解釋中添加更多細節。 raw_input()
,到目前爲止,您已經知道該操做能夠評估用戶以字符串形式輸入的數據。 這意味着python甚至不會嘗試再次理解輸入的數據。 它只會考慮輸入的數據將是字符串,不管它是實際的字符串仍是int或其餘任何值。 spa
另外一方面, input()
試圖理解用戶輸入的數據。 所以,像helloworld
這樣的輸入甚至會顯示錯誤,由於「 helloworld is undefined
」。 code
總之,對於python 2來講 ,也要輸入字符串,您須要像「 helloworld
」同樣輸入它,這是python中使用字符串的經常使用結構。 字符串
在Python 3中,Sven已經提到過raw_input()
不存在。 input
在Python 2中, input()
函數評估您的輸入。 string
例:
name = input("what is your name ?") what is your name ?harsha Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> name = input("what is your name ?") File "<string>", line 1, in <module> NameError: name 'harsha' is not defined
在上面的示例中,Python 2.x嘗試將rahda評估爲變量而不是字符串。 爲了不這種狀況,咱們能夠在輸入中使用雙引號,例如「 harsha」:
>>> name = input("what is your name?") what is your name?"harsha" >>> print(name) harsha
raw_input()
raw_input()函數不會求值,它只會讀取您輸入的內容。
例:
name = raw_input("what is your name ?") what is your name ?harsha >>> name 'harsha'
例:
name = eval(raw_input("what is your name?")) what is your name?harsha Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> name = eval(raw_input("what is your name?")) File "<string>", line 1, in <module> NameError: name 'harsha' is not defined
在上面的示例中,我只是嘗試使用eval
函數評估用戶輸入。
區別在於, raw_input()
在Python 3.x中不存在,而input()
則存在。 實際上,舊的raw_input()
已重命名爲input()
,舊的input()
消失了,可是能夠使用eval(input())
輕鬆地進行模擬。 (請記住eval()
是邪惡的。若是可能,請嘗試使用更安全的方法來解析輸入。)
在Python 2中 , raw_input()
返回一個字符串,而input()
嘗試將輸入做爲Python表達式運行。
因爲獲取字符串幾乎老是您想要的,所以Python 3使用input()
作到了。 正如Sven所說,若是您想要舊的行爲,則eval(input())
能夠工做。