Python:在字符串中查找子字符串并返回子字符串的索引 [英] Python: Find a substring in a string and returning the index of the substring

查看:234
本文介绍了Python:在字符串中查找子字符串并返回子字符串的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:


  • 一个函数: def find_str(s,char)

和一个字符串:生日快乐

我基本上想输入py并返回 3 但我会继续 2 返回。

I essentially want to input "py" and return 3 but I keep getting 2 to return instead.

代码:

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"))

不确定是什么问题!

推荐答案

理想情况下,您可以使用 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

这篇关于Python:在字符串中查找子字符串并返回子字符串的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆