字符串操纵是任何编程语言中常见的任务,Python提供两个常见的方法来检查一个字符串是否包含另一个字符串。
Python 检查 string 是否包含另一个 string
Python 字符串支持 in 操作员,所以我们可以用它来检查一个字符串是否是另一个字符串的一部分。
1sub in str
如果sub
字符串是str
的一部分,则返回True
,否则返回False
。
1str1 = 'I love Python Programming'
2
3str2 = 'Python'
4
5str3 = 'Java'
6
7print(f'"{str1}" contains "{str2}" = {str2 in str1}')
8print(f'"{str1}" contains "{str2.lower()}" = {str2.lower() in str1}')
9print(f'"{str1}" contains "{str3}" = {str3 in str1}')
10
11if str2 in str1:
12 print(f'"{str1}" contains "{str2}"')
13else:
14 print(f'"{str1}" does not contain "{str2}"')
输出:
1"I love Python Programming" contains "Python" = True
2"I love Python Programming" contains "python" = False
3"I love Python Programming" contains "Java" = False
4"I love Python Programming" contains "Python"
如果你不熟悉Python中的f前缀字符串,它是Python 3.6中引入的一种新的字符串格式方式。
当我们在操作员中使用时,它会内部调用 **containers() 函数,我们也可以直接使用此函数,但建议在操作员中使用以便可读性。
1s = 'abc'
2
3print('s contains a =', s.__contains__('a'))
4print('s contains A =', s.__contains__('A'))
5print('s contains X =', s.__contains__('X'))
输出:
1s contains a = True
2s contains A = False
3s contains X = False
使用 find() 来检查一个字符串是否包含另一个字符串
我们还可以使用 string find() 函数来检查 string 是否包含字符串。
1str1 = 'I love Python Programming'
2
3str2 = 'Python'
4
5str3 = 'Java'
6
7index = str1.find(str2)
8if index != -1:
9 print(f'"{str1}" contains "{str2}"')
10else:
11 print(f'"{str1}" does not contain "{str2}"')
12
13index = str1.find(str3)
14if index != -1:
15 print(f'"{str1}" contains "{str3}"')
16else:
17 print(f'"{str1}" does not contain "{str3}"')
输出:
1"I love Python Programming" contains "Python"
2"I love Python Programming" does not contain "Java"
您可以从我们的 GitHub 存储库中查阅完整的 Python 脚本和更多 Python 示例。