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

Tyler picture Tyler · Feb 18, 2014 · Viewed 194k times · Source

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.

Code:

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

Not sure what's wrong!

Answer

demented hedgehog picture demented hedgehog · Feb 18, 2014

There's a builtin method find on string objects.

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

find returns -1 if the string cannot be found.