我需要找到子字符串的第二次出现。如果没有第二次(或第一次)发生,程序应该相应地打印一条消息。
事件不能重叠。例如,在字符串"aa“中,子字符串”aa“的第二次出现在索引2处。
我刚接触过python,任何帮助都将不胜感激。下面是我的密码。
string=input("Please type in a string:")
substring=input("Please type in a substring:")
index=string.find(substring,string.find(substring)+1)
if index != -1 :
print(f"The second occurrence of the substring is at index {index}.")
else:
print("The substring does not occur twice in the string.")
当前代码将输出索引设为1而不是2。
发布于 2022-04-08 01:06:11
您需要更改find()
方法的开始索引。当您得到一个字符串时,您希望在第一次出现之后找到该字符的索引,所以使用find()
方法获取第一个出现的第一个字符的索引,并添加搜索单词的长度。
searched = "Mike"
sentence = "Hey ! Mike is with Mike"
sentence.find(searched) # 6
在这里,find()
方法返回6(搜索单词的第一个字符的索引),因此添加搜索单词(5)的长度,得到11。最后,得到以下结果:
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 does not occur twice in the string.")
https://stackoverflow.com/questions/71793912
复制