且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:在字符串中查找子字符串并返回子字符串的索引

更新时间:2022-05-06 06:15:06

理想情况下,您可以使用 str.find str.index 像疯狂的刺猬说。但是你说你不能......

Ideally you would use str.find or str.index like demented hedgehog said. But you said you can't ...

你的问题是你的代码只搜索你的搜索字符串的第一个字符(第一个字符)是索引2 。

Your problem is your code searches only for the first character of your search string which(the first one) is at index 2.

你基本上是说 char [0] 是否在 s ,增加 index 直到 ch == char [0] 我测试时返回3但是它还是错的这是一种方法。

You are basically saying if char[0] is in s, increment index until ch == char[0] which returned 3 when I tested it but it was still wrong. Here's a way to do it.

def find_str(s, char):
    index = 0

    if char in s:
        c = char[0]
        for ch in s:
            if ch == c:
                if s[index:index+len(char)] == char:
                    return index

            index += 1

    return -1

print(find_str("Happy birthday", "py"))
print(find_str("Happy birthday", "rth"))
print(find_str("Happy birthday", "rh"))

它产生以下输出:

3
8
-1