简体   繁体   中英

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 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>  

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

What else could I be missing?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM