Entering the command line raises a SyntaxError

I have a simple Python question about how my brains froze. This piece of code works. But when I replace "258 494-3929" with a phone number, 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 reand tried to use rstripin case\n

What else can I lose?

+5
source share
4 answers

You must use raw_inputinstead input, and you do not need to call str, because this function returns a string:

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

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

  • Reads a data string. (You want it.)
  • , Python. ( .)

raw_input() , # 1 , # 2.

:

input("Please enter a phone number: ")

:

raw_input("Please enter a phone number: ")

, Python.

input() , Python, Python 3.x . , input() 3.x , raw_input() 2.x.

. wikibooks.

+5

input() :

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

He is trying to evaluate '258 494-3929', which is not valid Python.

Use sys.stdin.readline().strip()for reading.

+4
source

input()calls eval(raw_input(prompt))so you wantphoneNumber = 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

+2
source

All Articles