命令行输入导致SyntaxError [英] Command-line input causes SyntaxError

查看:208
本文介绍了命令行输入导致SyntaxError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Python问题,我有大脑冻结。此代码段工作。但是当我用phoneNumber替换258 494-3929时,我得到以下错误:

 #比较电话号码
phone_pattern ='^ \d {3}?\d {3} -\d {4} $'

#phoneNumber = str(请输入电话号码: ))

如果re.search(phone_pattern,258 494-3929):
print模式匹配
else:
printPattern doesn t匹配!

##################### #########################################

 模式不匹配
请输入电话号码:258 494-3929
回溯(最近一次调用):
文件pattern_match.py​​,行16,in< module>
phoneNumber = str(input(Please enter a phone number:))
文件< string>,第1行
258 494-3929
^
语法错误:无效的语法

C:\Users\Developer \Documents\PythonDemo>


顺便说一下,我做了 import re 并在 \\\

解决方案

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

  phoneNumber = raw_input(请输入电话号码:)


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?

解决方案

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: ")

这篇关于命令行输入导致SyntaxError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆