簡體   English   中英

如何檢查字符串中的數字后面沒有跟字母?

[英]How can I check that a digit within a string is not followed by a letter?

CS50 問題集 2 - 印版作業是編寫一個程序來驗證印版輸入。 要求是:“所有虛榮板必須至少以兩個字母開頭。” “……個性牌最多可包含 6 個字符(字母或數字),最少包含 2 個字符。” “數字不能用在盤子中間; 他們必須在最后。 例如,AAA222 是可以接受的……化妝板; AAA22A 是不可接受的。 使用的第一個數字不能是‘0’。” “不允許使用句號、空格或標點符號。” 我的代碼有效,除了第三個要求:“數字不能在盤子中間使用......”我的代碼:

def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")

def is_valid(plate):
    # Check that there is no punctuation
    if not plate.isalnum():
        return False

    # Check that the length is from 2 to 6 characters
    if len(plate) < 2 or len(plate) > 6:
        return False

    # Check to see if the first two letters are alphanumeric
    if not plate[0:2].isalpha():
        return False

    # Check to see that numbers do not start with "0"
    for i in range(len(plate)):
        # If the current character is a number and the previous character is a letter,
        # check if the number is "0".
        if plate[i].isnumeric() and plate[i-1].isalpha() and plate[i] == "0":
            return False

    # Check to see that numbers are not in the middle - this is where the problem lies !
    plate = plate[::-1]
    for i in range(len(plate)):
        if plate[i].isnumeric() and plate[i-1].isalpha():
            return False

    # If all checks pass, return True
    return True
main()

is_valid 函數的最后一部分應該檢查數字后面是否沒有字母。 它確實將這些輸入返回為無效,但也會拒絕應該有效的輸入,例如“CS50”。 在上面的版本中,我顛倒了變量(plate)的順序,試圖查看數字是否跟在數字后面(不允許顛倒順序)。 我已經嘗試了 plate[i] 和 plate [i-1] 等的所有(我認為)組合。我嘗試用 isdigit() 代替 isnumeric(),但沒有成功。 我知道必須有其他方法來解決問題,但我真的很想了解為什么當上面的代碼起作用時這段代碼不起作用。 在 pythontutor.com 中運行代碼時,測試似乎在范圍末尾失敗,那里有兩個字母,這對我來說毫無意義。

您的索引有誤。

if plate[i].isnumeric() and plate[i-1].isalpha():

因為它是 python,所以在循環開始時, i-1環繞到字符串的末尾。 使用i+1i以相反的方式提出同樣的問題。

您需要將range()更改為開始和結束,以便不會發生翹曲。

你之前的檢查也存在同樣的問題。 您沒有注意到,因為還有一個附加條件,並且邊緣情況被第三次檢查過濾掉了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM