在Python中,我們可以使用內置的字符串函數或正則表達式來判斷一個字符串是否包含另一個字符串。
一、使用in關鍵字
def is_contain(str1, str2):
if str2 in str1:
return True
else:
return False
print(is_contain('hello world', 'hello')) #True
print(is_contain('hello world', 'hi')) #False
in關鍵字用於判斷一個字符串是否包含另一個字符串。這個方法簡單易懂,適用於一些簡單的字符串匹配。
二、使用find函數
def is_contain(str1, str2):
if str1.find(str2) != -1:
return True
else:
return False
print(is_contain('hello world', 'hello')) #True
print(is_contain('hello world', 'hi')) #False
find函數用於查找一個字符串在另一個字符串中的位置,如果找到,返回這個子字符串的位置,否則返回-1。由於in關鍵字只能判斷是否包含,而無法知道子字符串在字符串中的位置,因此find函數包含了in關鍵字的功能,並且可以知道子字符串在字符串中的位置。
三、使用正則表達式
import re
def is_contain(str1, str2):
pattern = re.compile(str2)
match = pattern.search(str1)
if match:
return True
else:
return False
print(is_contain('hello world', 'hello')) #True
print(is_contain('hello world', 'hi')) #False
正則表達式是一種強大的匹配模式,可以用於複雜的字符串匹配。在Python中,我們可以使用re模塊來使用正則表達式。上面的例子使用re.compile函數來編譯正則表達式並創建一個模式對象,然後使用模式對象的search方法來搜索字符串中的子字符串。如果找到匹配,返回MatchObject對象;如果沒有找到匹配,返回None。
四、結語
以上就是三種方法判斷Python中字符串是否包含另一個字符串。簡單的字符串匹配可以使用in關鍵字,如果需要知道子字符串在字符串中的位置,可以使用find函數。如果需要進行複雜的字符串匹配,比如模糊匹配、正則表達式匹配等,可以使用正則表達式。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/188944.html