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

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


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.


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 -1print(find_str("Happy birthday", "py"))print(find_str("Happy birthday", "rth"))print(find_str("Happy birthday", "rh"))

It produced the following output:

38-1


There is one other option in regular expression, the search method

import restring = 'Happy Birthday'pattern = 'py'print(re.search(pattern, string).span()) ## this prints starting and end indicesprint(re.search(pattern, string).span()[0]) ## this does what you wanted

By the way, if you would like to find all the occurrence of a pattern, instead of just the first one, you can use finditer method

import restring = 'i think that that that that student wrote there is not that right'pattern = 'that'print([match.start() for match in re.finditer(pattern, string)])

which will print all the starting positions of the matches.