Search for substring in string

Viewed 48

I'm having a problem of writing a function find_substr that takes two arguments as input: a substring and a string. And searches for substring and returns a tuple representing the (start, stop) of the substring.

For example

find_substr("plan", "I plan to join summer camp")
Output:
(2, 6) 

find_substr("su", "summer vacation")
Output:
(0, 2)

Which string methods I have to use to search for string and convert it to tuple?

2 Answers

you can use find method and do it like this:


String= "mohammed farhan mohammed almalki"

SupString = "farhan"

def FindMySupString(SupString,String):
    return (String.find(SupString),String.find(SupString)+len(SupString)-1)

Output will be like this:

(9, 14)

def find_substr(substring:str, string:str) -> tuple:
    start = string.find(substring)
    stop = start + len(substring)
    return (start, stop)

find_substr("plan", "I plan to join summer camp")

(2, 6)

Related