Python代码在空闲状态下工作,但在VS代码中不工作

Python代码在空闲状态下工作,但在VS代码中不工作,python,visual-studio-code,Python,Visual Studio Code,我现在开始学习Python,并选择了Al Sweigart的“用Python自动化无聊的东西”来帮助我完成第一步。因为我非常喜欢VisualStudio代码的外观和感觉,所以在本书的第一部分之后我尝试切换 以下代码来自在线资料,因此应该是正确的。不幸的是,它在空闲时可以正常工作,但在VS代码中不能 def isPhoneNumber(text): if len(text) != 12: return False # not phone number-sized

我现在开始学习Python,并选择了Al Sweigart的“用Python自动化无聊的东西”来帮助我完成第一步。因为我非常喜欢VisualStudio代码的外观和感觉,所以在本书的第一部分之后我尝试切换

以下代码来自在线资料,因此应该是正确的。不幸的是,它在空闲时可以正常工作,但在VS代码中不能

def isPhoneNumber(text):
    if len(text) != 12:
        return False  # not phone number-sized
    for i in range(0, 3):
        if not text[i].isdecimal():
            return False  # not an area code
    if text[3] != '-':
        return False  # does not have first hyphen
    for i in range(4, 7):
        if not text[i].isdecimal():
            return False  # does not have first 3 digits
    if text[7] != '-':
        return False  # does not have second hyphen
    for i in range(8, 12):
        if not text[i].isdecimal():
            return False  # does not have last 4 digits
    return True  # "text" is a phone number!

print('415-555-4242 is a phone number:')
print(isPhoneNumber('415-555-4242'))
print('Moshi moshi is a phone number:')
print(isPhoneNumber('Moshi moshi'))
我得到以下错误:

    415-555-4242 is a phone number: 
    Traceback (most recent call last):   
File "/Users/.../isPhoneNumber.py", line 20, in <module>
            print(isPhoneNumber('415-555-4242'))   
File "/Users/.../isPhoneNumber.py", line 5, in isPhoneNumber
            if not text[i].isdecimal(): AttributeError: 'str' object has no attribute 'isdecimal'
415-555-4242是一个电话号码:
回溯(最近一次呼叫最后一次):
文件“/Users/../isPhoneNumber.py”,第20行,在
打印(isPhoneNumber('415-555-4242'))
文件“/Users/../isPhoneNumber.py”,第5行,在isPhoneNumber中
如果不是文本[i]。isdecimal():AttributeError:'str'对象没有属性'isdecimal'
我很乐意听你的建议,让它发挥作用。我已经安装了Python扩展,并用pip3安装了建议的东西


提前感谢。

只有Unicode字符串具有isdecimal(),因此您必须将其标记为isdecimal()

要在python中将字符串转换为unicode字符串,可以执行以下操作:

s = "Hello!"
u = unicode(s, "utf-8")  
在您的问题中,您可以将
print(isPhoneNumber('415-555-4242'))
更改为
print(isPhoneNumber('415-555-4242'))
print(isPhoneNumber('Moshi Moshi'))
更改为
print(isPhoneNumber(u'Moshi Moshi Moshi'))

python中的u'string'确定字符串是unicode字符串


您使用的是什么python解释器?3.x字符串有
isdecimal
,但2.x没有。我不确定我具体使用的是哪个解释器。但是由于你的反应,我查了一下,把它改成了3.x解释器。现在它工作了!谢谢哇,谢谢。我以前不知道这个。换了翻译,现在可以了,没问题。将其标记为正确答案,以便对其他人有所帮助。我不知道所有unicode字符串都有
isdecimal
-谢谢!