Home > Enterprise >  Search for substring in string
Search for substring in string

Time:09-16

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?

CodePudding user response:

you can use find method and do it like this:


String= "mohammed farhan mohammed almalki"

SupString = "farhan"

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

Output will be like this:

(9, 14)

CodePudding user response:

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