这是来自一本 Python 书,代码抛出错误,应该这样做



我觉得我快疯了 - 我正在学习Python,并从Al Sweigart的Automate the Boring Stuff中获得了这段代码。

def isPhoneNumber(text):
    if len(text) !=12:
        return False
    for i in range(0, 3):
        if not text[i].isdecimal():
            return False
    if text[3] != '-':
        return False
    for i in range(4, 7):
        if not text[i].isdecimal():
            return False
    if text[7] != '-':
        return False
    for i in range(8, 12):
        if not text[i].isdecimal():
            return False
    return True
print(isPhoneNumber("192-343-2345"))

结果应该,并且确实返回错误,因为字符串对象没有 isDecimal 函数。我尝试在必要时将输入转换为 int 和 String,但它没有解决任何问题。我没有复制错误的代码,所以我不确定发生了什么?

这段代码在Python 3上工作正常。

您说字符串对象在 Python 2 中没有 isdecimal 函数是正确的。

如果你在Python 2中使用isdigit,它将起作用。

def isPhoneNumber(text):
    if len(text) !=12:
        return False
    for i in range(0, 3):
        if not text[i].isdigit():
            return False
    if text[3] != '-':
        return False
    for i in range(4, 7):
        if not text[i].isdigit():
            return False
    if text[7] != '-':
        return False
    for i in range(8, 12):
        if not text[i].isdigit():
            return False
    return True
print(isPhoneNumber("192-343-2345"))

最新更新