Home > database >  Define a procedure that finds the index of the second instance of a string in a a larger string
Define a procedure that finds the index of the second instance of a string in a a larger string

Time:11-09

I am new to python, may i know

Define a procedure that finds the index of the second instance of a string in a larger string.

def find_second(findin, whattofind):
      return 

find_second('dance, dance, dance everyday', 'dance')
find_second('learning about data, surprisingly, requires a lot of data','data')

CodePudding user response:

You can use the find() method of strings to know the position of a string inside another string. Since it allows you to specify where to start searching, you can ignore the first occurrence.

Check the following example:

def find_second(haystack, needle):
    first = haystack.find(needle)

    second = haystack.find(needle, first   1) # We add 1 to skip the first occurrence

    return second

This function returns the starting index of the second occurrence of the string needle found in haystack.

CodePudding user response:

Second index can be found by searching after the first index

You can use index() or find() for strings.

def find_second(findin, whattofind):
    return findin.index(whattofind,findin.index(whattofind) 1)

find_second('dance, dance, dance everyday', 'dance')
find_second('learning about data, surprisingly, requires a lot of data','data')
#output
7
53

Or with find()

def find_second(findin, whattofind):
    return findin.find(whattofind,findin.find(whattofind) 1)

print(find_second('dance, dance, dance everyday', 'dance'))
print(find_second('learning about data, surprisingly, requires a lot of data','data'))
#output
7
53
  • Related