在 Python 中檢查字串是否包含單詞
Muhammad Maisam Abbas
2023年10月10日
Python
Python String
本教程將介紹 Python 中查詢指定單詞是否在字串變數中的方法。
通過 Python 中的 if/in 語句檢查字串是否包含單詞
如果我們想檢查給定的字串中是否包含指定的單詞,我們可以使用 Python 中的 if/in 語句。if/in 語句返回 True 如果該詞出現在字串中,而 False 如果該詞不在字串中。
以下程式片段向我們展示瞭如何使用 if/in 語句來確定字串是否包含單詞:
string = "This contains a word"
if "word" in string:
print("Found")
else:
print("Not Found")
輸出:
Found
我們使用上面程式中的 if/in 語句檢查了字串變數 string 中是否包含單詞 word。這種方法按字元比較兩個字串;這意味著它不會比較整個單詞,並且可能會給我們錯誤的答案,如以下示例所示:
string = "This contains a word"
if "is" in string:
print("Found")
else:
print("Not Found")
輸出:
Found
輸出顯示單詞 is 出現在字串變數 string 中。但是,實際上,這個 is 只是 string 變數中第一個單詞 This 的一部分。
這個問題有一個簡單的解決方案。我們可以用空格將單詞和 string 變數括起來,以比較整個單詞。下面的程式向我們展示瞭如何做到這一點:
string = "This contains a word"
if " is " in (" " + string + " "):
print("Found")
else:
print("Not Found")
輸出:
Not Found
在上面的程式碼中,我們使用了相同的 if/in 語句,但我們稍微修改了它以僅比較單個單詞。這一次,輸出顯示在 string 變數中不存在 is 這樣的詞。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn