String manipulation is a common task in any programming language. Python provides two common ways to check if a string contains another string.
字符串操作是任何编程语言中的常见任务。 Python提供了两种常用方法来检查一个字符串是否包含另一个字符串。
Python检查字符串是否包含另一个字符串 (Python check if string contains another string)
Python string supports in operator. So we can use it to check if a string is part of another string or not. The in operator syntax is:
Python字符串支持in运算符。 因此,我们可以使用它来检查一个字符串是否是另一个字符串的一部分。 in运算符的语法为:
sub in str
It returns True
if “sub” string is part of “str”, otherwise it returns False
.
它返回True
,如果“子”字符串为“海峡”的一部分,否则返回False
。
Let’s look at some examples of using in
operator in Python.
让我们看一些在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}"')
Output:
输出:
"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"
When we use in operator, internally it calls __contains__() function. We can use this function directly too, however it’s recommended to use in operator for readability purposes.
当我们在运算符中使用时,在内部它会调用__contains __()函数。 我们也可以直接使用此功能,但是出于可读性考虑,建议在运算符中使用它。
s = 'abc'
print('s contains a =', s.__contains__('a'))
print('s contains A =', s.__contains__('A'))
print('s contains X =', s.__contains__('X'))
Output:
输出:
s contains a = True
s contains A = False
s contains X = False
使用find()检查一个字符串是否包含另一个子字符串 (Using find() to check if a string contains another substring)
We can also use string find() function to check if string contains a substring or not. This function returns the first index position where substring is found, else returns -1.
我们还可以使用string find()函数来检查string是否包含子字符串。 此函数返回找到子字符串的第一个索引位置,否则返回-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}"')
Output:
输出:
"I love Python Programming" contains "Python"
"I love Python Programming" does not contain "Java"
翻译自: https://www.journaldev.com/23795/python-check-if-string-contains-another-string