cos*_*son 7 python command-line input python-2.x
我有一个简单的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!"
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我做过import re并尝试过使用rstrip的情况\n
我还能错过什么?
sat*_*oru 12
你应该使用raw_input而不是input调用str,因为这个函数返回一个字符串本身:
phoneNumber = raw_input("Please enter a phone number: ")
Run Code Online (Sandbox Code Playgroud)
在Python 2.x版中,input()做了两件事:
函数raw_input()在这种情况下更好,因为它在#1之上但不在#2之上.
如果你改变:
input("Please enter a phone number: ")
Run Code Online (Sandbox Code Playgroud)
阅读:
raw_input("Please enter a phone number: ")
Run Code Online (Sandbox Code Playgroud)
你将消除电话号码不是有效Python表达式的错误.
input()函数已经绊倒了很多人学习Python,从Python版本3.x开始,该语言的设计者删除了额外的评估步骤.这使得版本3.x中的input()与版本2.x中的raw_input()行为相同.
另请参阅有用的wikibooks文章.
| 归档时间: |
|
| 查看次数: |
22530 次 |
| 最近记录: |