例如,字符串“chilchil”中,子字符串为“ch”,根据索引变量,“ch”第一次出现的索引为0,第二次出现的索引为2(0+2),但是实际上第二次出现是在 4 处,而不是 2 处。我希望得到解释。这是代码
string = input("Please type in a string: ")
substring = input("Please type in a substring: ")
index = string.find(substring, string.find(substring)+len(substring))
if index != -1:
print(f"The second occurrence of the substring is at index {index}")
else:
print("The substring doesn't occur twice in the string")
str.find的第二个参数,
start
,不会影响正在搜索的字符串,它只会影响搜索开始的位置。返回的索引仍然相对于原始字符串的开头。
看到之前的评论,我想你想要这样的东西
x="chilchil"
y="ch"
x[x.find(y)+len(y):].find(y)