004. python字符串查找(find, index等)

版权声明:欢迎联系我转载!欢迎交流分享!转载和分享请注明出处! https://blog.csdn.net/u014303046/article/details/82526173

Second index

一、题目描述

要求:给定两个字符串A和B,返回B在A中第二次出现的下标,如果未找到,返回None。

输入:2个字符串

输出:int or None

示例

second_index("sims", "s") == 3
second_index("find the river", "e") == 12
second_index("hi", " ") is None

二、解题示例

1. str.find()

def second_index(text: str, symbol: str) -> [int, None]:
    """
        returns the second index of a symbol in a given text
    """
    # your code here
    first_index = text.find(symbol)
    if first_index == -1:
        return None
    elif text[first_index+1:].find(symbol) == -1:
        return None
    else:
        return first_index + text[first_index+1:].find(symbol) + 1
    return text.find()


if __name__ == '__main__':
    print('Example:')
    print(second_index("sims", "s"))

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

2. str.index()

str.index(sub[, start[, end]])

def second_index(text: str, symbol: str):
    """
        returns the second index of symbol in a given text
    """
    try:
        return text.index(symbol, text.index(symbol) + 1)
    except ValueError:
        return None

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    print('Example:')
    print(second_index("sims", "s"))

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

3. str.find()说明

其实也可以用:text.find(symbol, text.find(symbol)+1)完成本题

但是要注意,找不到时的异常处理

4. 遍历法(简单粗暴)

def second_index(text, char):

    count = 0

    for i, c in enumerate(text):

        if c == char:
            count = count + 1
            if count == 2:
                return i

    return None


if __name__ == '__main__':
    print('Example:')
    print(second_index("sims", "s"))

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

猜你喜欢

转载自blog.csdn.net/u014303046/article/details/82526173