开发者

Command-line input causes SyntaxError

I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below:

# 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 ente开发者_运维百科r 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>  

By the way, I did import re and tried using rstrip in case of the \n

What else could I be missing?


You should use raw_input instead of input, and you don't have to call str, because this function returns a string itself:

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


In Python version 2.x, input() does two things:

  1. Reads a string of data. (You want this.)
  2. Then it evaluates the string of data as if it were a Python expression. (This part is causing the error.)

The function raw_input() is better in this situation because it does #1 above but not #2.

If you change:

input("Please enter a phone number: ")

to read:

raw_input("Please enter a phone number: ")

you'll eliminate the error of the phone number not being a valid Python expression.

The input() function has tripped up so many people learning Python that starting with Python versions 3.x, the designers of the language removed the extra evaluation step. This makes input() in versions 3.x behave the same as raw_input() in versions 2.x.

See also a helpful wikibooks article.


The input() function actually evaluates the input that's typed into it:

>>> print str(input("input: "))
input: 258238
258238
>>> print str(input("input: "))
input: 3**3 + 4
31

It's trying to evaluate '258 494-3929' which is invalid Python.

Use sys.stdin.readline().strip() to do your read.


input() calls eval(raw_input(prompt)), so you want phoneNumber = raw_input("Please enter a phone number: ").strip()

See also http://docs.python.org/library/functions.html#input and http://docs.python.org/library/functions.html#raw_input

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜