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


i have:

  • a function: def find_str(s, char)

  • and string: "happy birthday",

i want input "py" , return 3 keep getting 2 return instead.

code:

def find_str(s, char):     index = 0                if char in s:         char = char[0]         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!

ideally use str.find or str.index demented hedgehog said. said can't ...

your problem code searches first character of search string which(the first one) @ index 2.

you saying if char[0] in s, increment index until ch == char[0] returned 3 when tested still wrong. here's way it.

def find_str(s, char):     index = 0      if char in s:         c = char[0]         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 following output:

3 8 -1 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -