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

2024-03-29 09:34:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有:

  • 函数:def find_str(s, char)

  • 还有一个字符串:"Happy Birthday"

我基本上想输入"py"并返回3,但我一直让2返回。

代码:

def find_str(s, char):
    index = 0           
    if char in s:
        char = char[0]
        for ch in s:
            if ch in s:
                index += 1
            if ch == char:
                return index

    else:
        return -1

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

不知道怎么了!


Tags: 函数字符串代码inpyindexreturnif
3条回答

理想情况下,您可以使用str.findstr.index就像疯了的刺猬说的那样。但你说你不能。。。

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

你基本上是说,如果char[0]s中,则递增index,直到ch == char[0]在我测试时返回3,但仍然是错误的。这是一种方法。

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

晚到派对,正在寻找相同的,作为“在”是无效的,我刚刚创建了以下。

def find_str(full, sub):
    index = 0
    sub_index = 0
    position = -1
    for ch_i,ch_f in enumerate(full) :
        if ch_f.lower() != sub[sub_index].lower():
            position = -1
            sub_index = 0
        if ch_f.lower() == sub[sub_index].lower():
            if sub_index == 0 :
                position = ch_i

            if (len(sub) - 1) <= sub_index :
                break
            else:
                sub_index += 1

    return position

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

产生

3
8
-1

在不区分大小写的情况下,删除lower(),不需要查找。

在python中有一个关于字符串对象的内置方法可以做到这一点,你知道吗?

s = "Happy Birthday"
s2 = "py"

print s.find(s2)

Python是一种“包含电池的语言”,有编写代码来完成大多数您想要的事情(无论您想要什么)。。除非这是家庭作业:)

编辑:find如果找不到字符串,则返回-1。

相关问题 更多 >