Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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!

like image 829
Tyler Avatar asked Feb 18 '14 01:02

Tyler


People also ask

How do you find the index of a substring in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you find the first index of a substring in a given string in Python?

Use the find() Function to Find First Occurrence in Python We can use the find() function in Python to find the first occurrence of a substring inside a string. The find() function takes the substring as an input parameter and returns the first starting index of the substring inside the main string.

How do you find the substring of a string in Python?

Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found then it returns -1. Parameters: sub: It is the substring that needs to be searched in the given string.


1 Answers

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.

like image 100
demented hedgehog Avatar answered Oct 03 '22 04:10

demented hedgehog