这里有人可以向我解释一下这段代码中的第三行如何处理两个字符的子字符串吗?

问题描述 投票:0回答:2

例如,字符串“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")
python indexing substring
2个回答
1
投票

str.find的第二个参数,

start
,不会影响正在搜索的字符串,它只会影响搜索开始的位置。返回的索引仍然相对于原始字符串的开头。


0
投票

看到之前的评论,我想你想要这样的东西

x="chilchil"
y="ch"
x[x.find(y)+len(y):].find(y)
© www.soinside.com 2019 - 2024. All rights reserved.