[英]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.