簡體   English   中英

設置字符串輸入以接受來自可接受答案數組的答案(Python 3.8.4)

[英]Set a string input to accept an answer from an array of acceptable answers (Python 3.8.4)

#important variables
thePhrase = input("What phrase will we be dealing with today?")
menuInput = input("What would you like to do with the phrase?") 

#search query tables
phraseLenArray = ["LEN", "LENGTH", "TEXT LENGTH", "PHRASE LENGTH", "STRING LENGTH", "LENGTH OF THE TEXT", "LENGTH OF THE PHRASE", "LENGTH OF THE STRING", "HOW LONG IS THE TEXT", "HOW LONG IS THE PHRASE", "HOW LONG IS THE STRING"]
phraseFilterArray = ["FILTER", "FILTER THE TEXT", "FILTER THE PHRASE", "FILTER THE STRING",]


if menuInput == phraseLenArray.lower():
    phraseLen()
elif menuInput == phraseFilterArray.lower():
        phraseFilter()


def phraseLen():
    print(len(thePhrase))

def phraseFilter():
    filterTxt = input("What are you trying to filter for?")
    if filterTxt in thePhrase:
        print("The filtered text,", filterTxt, "was found in the text.")
    else:
        print("The filtered text was not found in the text")

我試圖讓輸入“menuInput”接受來自 arrays 的答案,不區分大小寫。 當我運行此代碼時,錯誤消息是“第 10 行:AttributeError:'list' object 沒有屬性 'lower'”

phraseLenArray是一個列表。 當您嘗試將列表轉換為大寫時,會引發錯誤。 我對您的代碼做了一些更改。

首先,總是在調用函數之前定義它們。 在這里,您正在遵循程序編程,並且 python 從上到下讀取。 當遇到在調用 function定義的 function 時,它會引發錯誤。

其次,您可以使用.upper()將輸入轉換為大寫字母。

這是代碼;

thePhrase = input("What phrase will we be dealing with today?")
menuInput = input("What would you like to do with the phrase?") 

#search query tables
phraseLenArray = ["LEN", "LENGTH", "TEXT LENGTH", "PHRASE LENGTH", "STRING LENGTH", "LENGTH OF THE TEXT", "LENGTH OF THE PHRASE", "LENGTH OF THE STRING", "HOW LONG IS THE TEXT", "HOW LONG IS THE PHRASE", "HOW LONG IS THE STRING"]
phraseFilterArray = ["FILTER", "FILTER THE TEXT", "FILTER THE PHRASE", "FILTER THE STRING",]
def phraseLen():
    print(len(thePhrase))

def phraseFilter():
    filterTxt = input("What are you trying to filter for?")
    if filterTxt in thePhrase:
        print("The filtered text,", filterTxt, "was found in the text.")
    else:
        print("The filtered text was not found in the text")

if menuInput.upper() in phraseLenArray:
    phraseLen()
elif menuInput.upper() in phraseFilterArray:
    phraseFilter()


如錯誤所述, phraseLenArray是一個列表,因此沒有lower方法。 您可以嘗試將 menuInput 大寫:

if menuInput.upper() in phraseLenArray:

或使用 map 和 lambda:

if menuInput in map(lambda s: s.lower(), phraseLenArray):

嘗試這個:

for phraseLen in phraseLenArray:
    if phraseLen == menuInput:
        phraseLen()

function lower()string而不是list的屬性,因此您需要使用 for 循環(或其他方式)來獲取list的項目並將它們與您的menuInput進行比較。

暫無
暫無

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

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