You are given two strings and you have to find an index of the second occurrence of the second string in the first one.
Let's go through the first example where you need to find the second occurrence of "s" in a word "sims". It’s easy to find its first occurrence with a function index or find which will point out that "s" is the first symbol in a word "sims" and therefore the index of the first occurrence is 0. But we have to find the second "s" which is 4th in a row and that means that the index of the second occurrence (and the answer to a question) is 3.
Input: Two strings.
Output: Int or None
Example:
second_index("sims", "s") == 3 second_index("find the river", "e") == 12 second_index("hi", " ") is None
您将获得两个字符串,您必须在第一个字符串中找到第二个字符串第二次出现的索引。让我们来看看第一个例子,你需要在单词“sims”中找到第二次出现的“s”。很容易找到它的第一个出现的函数索引或find将指出“s”是单词“sims”中的第一个符号,因此第一次出现的索引是0.但我们必须找到第二个“s“这是连续第4次,这意味着第二次出现的索引(和问题的答案)是3。 输入:两个字符串。 输出:Int或None
def second_index(text: str, symbol: str) -> [int, None]:
"""
returns the second index of a symbol in a given text
"""
# your code here
if text.count(symbol) < 2: # 如果找到数量小于2即只有一个 按照要求返回none
return None
# 先找到一个的字符的索引 然后从此索引开始查找 再次第一次找到的索引即为我们需要的第二次的索引
return text.find(symbol, text.find(symbol) + 1)
if __name__ == '__main__':
print('Example:')
print(second_index("hi", " "))
# These "asserts" are used for self-checking and not for an auto-testing
assert second_index("sims", "s") == 3, "First"
assert second_index("find the river", "e") == 12, "Second"
assert second_index("hi", " ") is None, "Third"
assert second_index("hi mayor", " ") is None, "Fourth"
assert second_index("hi mr Mayor", " ") == 5, "Fifth"
print('You are awesome! All tests are done! Go Check it!')