命令行输入会导致SyntaxError

时间:2010-04-07 00:43:37

标签: python input command-line 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!"  

 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并尝试使用rstrip \n

我还能错过什么?

4 个答案:

答案 0 :(得分:11)

您应该使用raw_input而不是input,而不必调用str,因为此函数本身会返回一个字符串:

phoneNumber = raw_input("Please enter a phone number: ")

答案 1 :(得分:8)

在Python 2.x版中,input()做了两件事:

  1. 读取一串数据。 (你想要这个。)
  2. 然后它评估数据字符串,就好像它是一个Python表达式。 (这部分导致错误。)
  3. 函数raw_input()在这种情况下更好,因为它在#1上面但不在#2上。

    如果你改变:

    input("Please enter a phone number: ")
    

    阅读:

    raw_input("Please enter a phone number: ")
    

    您将消除电话号码不是有效Python表达式的错误。

    输入()函数已经绊倒了很多人学习Python,从Python版本3.x开始,该语言的设计者删除了额外的评估步骤。这使得3.x版本中的input()与版本2.x中的raw_input()行为相同。

    另见a helpful wikibooks article

答案 2 :(得分:4)

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()进行阅读。

答案 3 :(得分:2)

input()来电eval(raw_input(prompt)),您需要phoneNumber = raw_input("Please enter a phone number: ").strip()

另请参阅http://docs.python.org/library/functions.html#inputhttp://docs.python.org/library/functions.html#raw_input

相关问题