checkio练习题:second-index

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!')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值