在Python中,可以使用字符串的find()方法来查找子字符串。find()方法返回子字符串在父字符串中第一次出现的索引位置。如果子字符串不存在,则返回-1。
以下是一个示例:
string = "Hello, world!"sub_string = "world"index = string.find(sub_string)print(index) # 输出: 7你可以使用find()方法来查找字符串中的多个子字符串。以下是一个示例:
string = "Hello, world!"sub_string1 = "Hello"sub_string2 = "world"index1 = string.find(sub_string1)index2 = string.find(sub_string2)print(index1) # 输出: 0print(index2) # 输出: 7另外,还可以使用index()方法来查找子字符串。index()方法与find()方法类似,但是如果子字符串不存在,则会抛出ValueError异常。
以下是一个使用index()方法的示例:
string = "Hello, world!"sub_string = "world"try: index = string.index(sub_string) print(index)except ValueError: print("子字符串不存在")这些方法可以帮助你在字符串中查找子字符串。

