字串操作是任何程式語言中常見的任務。Python 提供了兩種常見的方法來檢查一個字串是否包含另一個字串。
Python 檢查字串是否包含另一個字串
Python 字串支援 in 運算子。因此,我們可以使用它來檢查一個字串是否是另一個字串的一部分。 in 運算子的語法是:
sub in str
如果“sub”字串是“str”的一部分,它將返回 True
,否則將返回 False
。讓我們看一些在 Python 中使用 in
運算子的示例。
str1 = 'I love Python Programming'
str2 = 'Python'
str3 = 'Java'
print(f'"{str1}" contains "{str2}" = {str2 in str1}')
print(f'"{str1}" contains "{str2.lower()}" = {str2.lower() in str1}')
print(f'"{str1}" contains "{str3}" = {str3 in str1}')
if str2 in str1:
print(f'"{str1}" contains "{str2}"')
else:
print(f'"{str1}" does not contain "{str2}"')
輸出:
"I love Python Programming" contains "Python" = True
"I love Python Programming" contains "python" = False
"I love Python Programming" contains "Java" = False
"I love Python Programming" contains "Python"
如果您不熟悉 Python 中的 f-字串,這是一種新的字串格式化方式,引入於 Python 3.6。您可以在 Python 中的 f-字串 中閱讀更多相關資訊。
當我們使用 in 運算子時,內部實際上調用了 __contains__() 函數。我們也可以直接使用這個函數,但建議出於可讀性考慮使用 in 運算子。
s = 'abc'
print('s contains a =', s.__contains__('a'))
print('s contains A =', s.__contains__('A'))
print('s contains X =', s.__contains__('X'))
輸出:
s contains a = True
s contains A = False
s contains X = False
使用 find() 方法檢查字串是否包含另一個子字串
我們也可以使用 string find() 函數 來檢查字串是否包含子字串。此函數返回子字串被找到的第一個索引位置,否則返回 -1。
str1 = 'I love Python Programming'
str2 = 'Python'
str3 = 'Java'
index = str1.find(str2)
if index != -1:
print(f'"{str1}" contains "{str2}"')
else:
print(f'"{str1}" does not contain "{str2}"')
index = str1.find(str3)
if index != -1:
print(f'"{str1}" contains "{str3}"')
else:
print(f'"{str1}" does not contain "{str3}"')
輸出:
"I love Python Programming" contains "Python"
"I love Python Programming" does not contain "Java"
您可以從我們的 GitHub Repository 中查看完整的 Python 腳本和更多 Python 示例。
Source:
https://www.digitalocean.com/community/tutorials/python-check-if-string-contains-another-string