[英]Command-line input causes SyntaxError
我有一個簡單的Python問題,我的大腦停滯不前。 此代碼段有效。 但是,當我用phoneNumber替換“ 258 494-3929”時,出現以下錯誤:
# Compare phone number
phone_pattern = '^\d{3} ?\d{3}-\d{4}$'
# phoneNumber = str(input("Please enter a phone number: "))
if re.search(phone_pattern, "258 494-3929"):
print "Pattern matches"
else:
print "Pattern doesn't match!"
Pattern does not match
Please enter a phone number: 258 494-3929
Traceback (most recent call last):
File "pattern_match.py", line 16, in <module>
phoneNumber = str(input("Please enter a phone number: "))
File "<string>", line 1
258 494-3929
^
SyntaxError: invalid syntax
C:\Users\Developer\Documents\PythonDemo>
順便說一句,我確實import re
並在\\n
情況下嘗試使用rstrip
我還能缺少什么?
您應該使用raw_input
而不是input
,並且不必調用str
,因為此函數本身返回一個字符串:
phoneNumber = raw_input("Please enter a phone number: ")
在Python 2.x版中,input()做兩件事:
在這種情況下,函數raw_input()更好,因為它執行上面的#1而不是#2。
如果您更改:
input("Please enter a phone number: ")
讀書:
raw_input("Please enter a phone number: ")
您將消除電話號碼不是有效的Python表達式的錯誤。
input()函數讓學習Python的人們trip之以鼻,以至於Python版本3.x開始,該語言的設計人員取消了額外的評估步驟。 這使得3.x版中的input()的行為與2.x版中的raw_input()相同。
另請參閱有用的Wikibooks文章 。
input()函數實際上會評估輸入到其中的輸入:
>>> print str(input("input: "))
input: 258238
258238
>>> print str(input("input: "))
input: 3**3 + 4
31
它正在嘗試評估'258 494-3929',這是無效的Python。
使用sys.stdin.readline().strip()
進行閱讀。
input()
調用eval(raw_input(prompt))
,因此您需要phoneNumber = raw_input("Please enter a phone number: ").strip()
另請參見http://docs.python.org/library/functions.html#input和http://docs.python.org/library/functions.html#raw_input
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.