python七種方法判斷字串是否包含子串
1. 使用 in 和 not in
in 和 not in 在 Python 中是很常用的關鍵字,我們將它們歸類為 成員運算子。
使用這兩個成員運算子,可以很讓我們很直觀清晰的判斷一個物件是否在另一個物件中,示例如下:
>>> "llo" in "hello,python" True >>> >>> "lol" in "hello,python" False
2. 使用 find 方法
使用 字串 物件的 find 方法,如果有找到子串,就可以返回指定子串在字串中的出現位置,如果沒有找到,就返回 -1
>>> "hello,python".find("llo") != -1 True >>> "hello,python".find("lol") != -1 False >>
3. 使用 index 方法
字串物件有一個 index 方法,可以返回指定子串在該字串中第一次出現的索引,如果沒有找到會丟擲異常,因此使用時需要注意捕獲。
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,"lol")) # False
4. 使用 count 方法
利用和 index 這種曲線救國的思路,同樣我們可以使用 count 的方法來判斷。
只要判斷結果大於 0 就說明子串存在於字串中。
def is_in(full_str,sub_str): return full_str.count(sub_str) > 0 print(is_in("hello,"lol")) # False
5. 通過魔法方法
在第一種方法中,我們使用 in 和 not in 判斷一個子串是否存在於另一個字元中,實際上當你使用 in 和 not in 時,Python 直譯器會先去檢查該物件是否有 __contains__ 魔法方法。
若有就執行它,若沒有,Python 就自動會迭代整個序列,只要找到了需要的一項就返回 True 。
示例如下:
>>> "hello,python".__contains__("llo") True >>> >>> "hello,python".__contains__("lol") False >>>
這個用法與使用 in 和 not in 沒有區別,但不排除有人會特意寫成這樣來增加程式碼的理解難度。
6. 藉助 operator
operator模組是python中內建的操作符函式介面,它定義了一些算術和比較內建操作的函式。operator模組是用c實現的,所以執行速度比 python 程式碼快。
在 operator 中有一個方法 contains 可以很方便地判斷子串是否在字串中。
>>> import operator >>> >>> operator.contains("hello,"llo") True >>> operator.contains("hello,"lol") False >>>
7. 使用正則匹配
說到查詢功能,那正則絕對可以說是專業的工具,多複雜的查詢規則,都能滿足你。
對於判斷字串是否存在於另一個字串中的這個需求,使用正則簡直就是大材小用。
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,"lol")) # False
以上就是python七種方法判斷字串是否包含子串的詳細內容,更多關於python 字串的資料請關注我們其它相關文章!