Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 802
coson Avatar asked Apr 07 '10 00:04

coson


People also ask

How do I fix Python SyntaxError?

You can clear up this invalid syntax in Python by switching out the semicolon for a colon. Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.

What causes a SyntaxError in Python?

Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.

Why is my else invalid syntax Python?

In Python code in a file, there can't be any other code between the if and the else . You'll see SyntaxError: invalid syntax if you try to write an else statement on its own, or put extra code between the if and the else in a Python file.

How do you use the input function?

In Python, we use input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function convert it into a string.


1 Answers

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: ")
like image 57
satoru Avatar answered Oct 21 '22 00:10

satoru