欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

4種python判斷字符串是否包含關(guān)鍵字的方法

 更新時間:2025年04月09日 10:16:32   作者:alden_ygq  
這篇文章主要為大家詳細(xì)介紹了4種python判斷字符串是否包含關(guān)鍵字的方法,文中的示例代碼講解詳細(xì),有需要的小伙伴可以根據(jù)自己的需求進(jìn)行選擇

方法 1:使用 in 關(guān)鍵字(最簡潔)

直接通過 in 操作符檢查子字符串是否存在:

text = "Hello, welcome to Python world."
keyword = "Python"
 
if keyword in text:
    print(f"包含關(guān)鍵字 '{keyword}'")
else:
    print(f"不包含關(guān)鍵字 '{keyword}'")

方法 2:使用 str.find() 方法

find() 返回子字符串的起始索引(未找到則返回 -1):

text = "Hello, welcome to Python world."
keyword = "Python"
 
if text.find(keyword) != -1:
    print("關(guān)鍵字存在")
else:
    print("關(guān)鍵字不存在")

方法 3:使用 str.index() 方法

與 find() 類似,但未找到時會拋出 ValueError 異常:

try:
    index = text.index(keyword)
    print(f"關(guān)鍵字在索引 {index} 處")
except ValueError:
    print("關(guān)鍵字不存在")

方法 4:正則表達(dá)式(復(fù)雜匹配)

使用 re 模塊實(shí)現(xiàn)更靈活的匹配(如忽略大小寫、模糊匹配等):

import re
 
text = "Hello, welcome to Python world."
pattern = r"python"  # 正則表達(dá)式模式
 
if re.search(pattern, text, re.IGNORECASE):  # 忽略大小寫
    print("關(guān)鍵字存在")
else:
    print("關(guān)鍵字不存在")

擴(kuò)展場景

1. 檢查多個關(guān)鍵字是否存在

使用 any() 結(jié)合生成器表達(dá)式:

keywords = ["Python", "Java", "C++"]
text = "I love Python programming."
 
if any(k in text for k in keywords):
    print("至少包含一個關(guān)鍵字")

2. 統(tǒng)計(jì)關(guān)鍵字出現(xiàn)的次數(shù)

使用 str.count():

count = text.count("Python")
print(f"關(guān)鍵字出現(xiàn)了 {count} 次")

知識擴(kuò)展

Python判斷字符串是否包含特定子串的7種方法

我們經(jīng)常會遇這樣一個需求:判斷字符串中是否包含某個關(guān)鍵詞,也就是特定的子字符串。比如從一堆書籍名稱中找出含有“python”的書名。

判斷兩個字符串相等很簡單,直接 == 就可以了。其實(shí)判斷包含子串也非常容易,而且還不止一種方法。下面我們就給大家分享 7 種可以達(dá)到此效果的方法:

1、使用 in 和 not in

innot inPython 中是很常用的關(guān)鍵字,我們將它們歸類為成員運(yùn)算符。

使用這兩個成員運(yùn)算符,可以很讓我們很直觀清晰的判斷一個對象是否在另一個對象中,示例如下:

>>> "llo" in "hello, python"
True
>>>
>>> "lol" in "hello, python"
False

2、使用 find 方法

使用 字符串 對象的 find 方法,如果有找到子串,就可以返回指定子串在字符串中的出現(xiàn)位置,如果沒有找到,就返回 -1

>>> "hello, python".find("llo") != -1
True
>>> "hello, python".find("lol") != -1
False
>>

3、使用 index 方法

字符串對象有一個 index 方法,可以返回指定子串在該字符串中第一次出現(xiàn)的索引,如果沒有找到會拋出異常,因此使用時需要注意捕獲。

def is_in(full_str, sub_str):
    try:
        full_str.index(sub_str)
        return True
    except ValueError:
        return False

print(is_in("hello, python", "llo"))  # True
print(is_in("hello, python", "lol"))  # False

4、使用 count 方法

利用和 index 這種曲線救國的思路,同樣我們可以使用 count 的方法來判斷。

只要判斷結(jié)果大于 0 就說明子串存在于字符串中。

def is_in(full_str, sub_str):
    return full_str.count(sub_str) > 0

print(is_in("hello, python", "llo"))  # True
print(is_in("hello, python", "lol"))  # False

5、通過魔法方法

在第一種方法中,我們使用 innot in 判斷一個子串是否存在于另一個字符中,實(shí)際上當(dāng)你使用 innot in 時,Python 解釋器會先去檢查該對象是否有__contains__魔法方法。

若有就執(zhí)行它,若沒有,Python 就自動會迭代整個序列,只要找到了需要的一項(xiàng)就返回 True

示例如下;

>>> "hello, python".__contains__("llo")
True
>>>
>>> "hello, python".__contains__("lol")
False
>>>

這個用法與使用 innot in 沒有區(qū)別,但不排除有人會特意寫成這樣來增加代碼的理解難度。

6、借助 operator

operator模塊是 python 中內(nèi)置的操作符函數(shù)接口,它定義了一些算術(shù)和比較內(nèi)置操作的函數(shù)。operator模塊是用 c 實(shí)現(xiàn)的,所以執(zhí)行速度比 python 代碼快。

operator 中有一個方法 contains 可以很方便地判斷子串是否在字符串中。

>>> import operator
>>>
>>> operator.contains("hello, python", "llo")
True
>>> operator.contains("hello, python", "lol")
False
>>> 

7、使用正則匹配

說到查找功能,那正則絕對可以說是專業(yè)的工具,多復(fù)雜的查找規(guī)則,都能滿足你。

對于判斷字符串是否存在于另一個字符串中的這個需求,使用正則簡直就是大材小用。

import re

def is_in(full_str, sub_str):
    if re.findall(sub_str, full_str):
        return True
    else:
        return False

print(is_in("hello, python", "llo"))  # True
print(is_in("hello, python", "lol"))  # False

總結(jié)

推薦使用 in 操作符:簡單高效,適用于大多數(shù)場景。

正則表達(dá)式:適合需要模糊匹配(如大小寫不敏感、模式匹配)的場景。

避免冗余代碼:優(yōu)先選擇直接判斷邏輯(如 if keyword in text)。

到此這篇關(guān)于4種python判斷字符串是否包含關(guān)鍵字的方法的文章就介紹到這了,更多相關(guān)python判斷字符串是否含關(guān)鍵字內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論