Python: Find a substring in a string and returning the index of the substring


I have:

  • a function: def find_str(s, char)

  • and a string: "Happy Birthday",

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

        return -1

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

Not sure what's wrong!

12/16/2016 2:08:18 PM

Accepted Answer

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

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

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

It produced the following output:

2/3/2017 3:51:12 PM

There's a builtin method on string objects to do this in python you know?

s = "Happy Birthday"
s2 = "py"

print s.find(s2)

Python is a "batteries included language" there's code written to do most of what you want already (whatever you want).. unless this is homework :)

Edit: find returns -1 if the string cannot be found.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow