簡體   English   中英

我需要在字符串中搜索一個單詞,如何使其不區分大小寫?

[英]I need to search a string for a word, how do i make it case insensitive?

到目前為止,這是我的代碼

sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
keyword.upper() == keyword.lower()
words = sentence.split(' ')
for (i, subword) in enumerate(words)  
    if (subword == keyword)  
        print(i+1)
if (keyword not in sentence)  
    print("Sorry, that word wasnt found in the sentence")

以下不起作用

keyword.upper() == keyword.lower()

我可以在代碼中添加什么?

通常,您可以使用in關鍵字檢查子字符串是否是另一個字符串的一部分:

sentence = input("Sentence: ")
keyword = input("Keyword: ")

if keyword in sentence:
    print("Found it!")
else:
    print("It's not there...")

要變得不區分大小寫,您必須將句子的小寫版本與關鍵字的小寫版本進行比較(或兩者都使用大寫形式,沒有區別):

if keyword.lower() in sentence.lower():
    # ...

我可以看到您嘗試將upper()和lower()設置為相同值的邏輯,但是這樣做並不是很有效。

在比較子詞和關鍵字的地方,您需要同時調用.upper()或.lower(),以便它們都總是小寫或大寫。

您必須像這樣更改代碼:

sentence= input("Enter a sentence")
keyword = input("Input a keyword from the sentence").lower()
Found   = False
words   = sentence.split(' ')
for (i, subword) in enumerate(words)  
    if (subword.lower() == keyword)  
        print('keyword found at position', i+1)
        Found = True
if not found:  
    print("Sorry, that word wasn't found in the sentence")

暫無
暫無

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

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