在Python中,表示字符串或其他可迭代对象的包含关系,可以使用`in`关键字。下面是一些示例:
str_test = "the family can mutually close cooperation, is the only real happiness in the world."
str2 = "family"
if str2 in str_test:
print(f"'{str2}' found in the string")
else:
print(f"'{str2}' not found here")
2. 使用`find`方法查找子字符串在字符串中的位置,返回子字符串第一次出现的索引值,如果不存在则返回-1:
str_test = "the family can mutually close cooperation, is the only real happiness in the world."
str2 = "family"
if str_test.find(str2) == -1:
print(f"'{str2}' not found here")
else:
print(f"'{str2}' found at index {str_test.find(str2)}")
3. 使用`rfind`方法查找子字符串在字符串中从后往前的位置,返回子字符串最后一次出现的索引值,如果不存在则返回-1:
str_test = "the family can mutually close cooperation, is the only real happiness in the world."
str2 = "family"
if str_test.rfind(str2) == -1:
print(f"'{str2}' not found here")
else:
print(f"'{str2}' found at index {str_test.rfind(str2)}")
4. 使用`index`方法查找子字符串在字符串中的位置,如果不存在则抛出异常:
str_test = "the family can mutually close cooperation, is the only real happiness in the world."
str2 = "family"
try:
index = str_test.index(str2)
print(f"'{str2}' found at index {index}")
except ValueError:
print(f"'{str2}' not found here")
以上示例展示了如何使用Python中的不同方法来表示字符串的包含关系。