2017-10-08 54 views
0

我覺得我要瘋了 - 我正在學習Python,並從Al Sweigart的Automate the Boring Stuff中獲得此代碼。這是來自一本Python書,代碼拋出錯誤,應該這樣做

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,但它不能解決任何問題。我沒有複製錯誤的代碼,所以我不確定發生了什麼事情?

+3

如果函數*應該引發錯誤,並且引起錯誤,那麼問題是什麼?你想達到什麼目的? – jwodder

+0

你的意思是'isdigit'? – jonrsharpe

回答

2

此代碼工作正常Python的3

你是說字符串對象正確在Python中沒有isdecimal功能2.

如果你在Python 2

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")) 
使用 isdigit它將工作
相關問題