App下載

Python 屬性錯誤:'NoneType怎么解決?

猿友 2021-07-22 14:14:02 瀏覽數(shù) (4631)
反饋

今天W3Cschool為大家?guī)淼氖荘ython 屬性錯誤:'NoneType怎么解決,希望能對各位正在學(xué)習(xí)python的朋友有所幫助。

我是Python擴展Regex的新手。我試圖做一個迷你python Regex項目,我遇到了一個問題。我只是想查個電話號碼。如果你輸入正確的數(shù)字,你會收到“thank you”,但如果你輸入隨機數(shù)字(不是電話號碼)或隨機字母,你會收到“Try again”。

問題是,如果我輸入一個字母,然后我收到一個AttributeError: 'NoneType'對象沒有屬性'group '。

這是一個解決方案:

import re
import time


print('Welcome, you have won 1 million dollars! Please verify your phone number!')
time.sleep(2) #sleep
content = input('Please enter your number:')
# content = "111-111-1111"
numberRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
result = numberRegex.search(content)
if result is not None:
    time.sleep(3) #sleep
    if result.group() == content:
        print('thank you')

    if result.group() != content:
        print('try again')
else:
    print('try again')

另一種解決方案是嘗試/捕獲塊處理異常。

我猜它永遠(yuǎn)不會得到代碼的這一部分:

if result.group() != content:
        print('try again')

但我離開了它現(xiàn)在,因為我不是真的熟悉蟒蛇的regex圖書館


0 人點贊