90.8k views
1 vote
#Write a function called after_second that accepts two #arguments: a target string to search, and string to search #for. The function should return everything in the first #string *after* the *second* occurrence of the search term. #You can assume there will always be at least two #occurrences of the search term in the first string. # #For example: # after_second("11223344554321", "3") -> 44554321 # #The search term "3" appears at indices 4 and 5. So, this #returns everything from the index 6 to the end. # # after_second("heyyoheyhi!", "hey") -> hi! # #The search term "hey" appears at indices 0 and 5. The #search term itself is three characters. So, this returns #everything from the index 8 to the end. # #Hint: This may be more complicated than it looks! You'll #have to look at the length of the search string and #either modify the target string or take advantage of the #extra arguments you can pass to find(). #Write your function here!

User Sabiwara
by
4.3k points

1 Answer

3 votes

Answer:

Following are the code to this question:

def after_second(s,sub):#defining a method a fter_second

first = s.find(sub)#defining a variable first that hold method find value

if first != -1:#defining if block to check first variable value not equal to -1 using slicing

s = s[len(sub)+first:]#defining s variable to calculate sub parameter length of parameter and use slicing

second = s.find(sub)#defining second variable to calculate find method value

if second != -1:#defining if block to calculate second variable slicing

return s[len(sub)+second:]#return s variable value

print(after_second("heyyoheyhi","hey"))#defining print method to call after_second method

print(after_second("11223344554321","3"))#defining print method to call after_second method

Output:

hi

44554321

Step-by-step explanation:

In the above python code a method "after_second" is declared, that accepts two-variable "s, and sub" as the parameter inside the method a first variable is declared that uses the inbuilt method "find" to find the value and stores it value. In the next step, two if blocks are used, in which both if blocks use the slicing to checks its value is not equal to "-1".

  • In the first, if block the first variable is declared that uses the s variable to calculate subparameter length by using slicing and defines the second variable that finds its value and stores its value.
  • In the next, if block the s variable is used to return its calculated value, and at the end of the print, the method is used to call the method by passing parameter value and prints its return value.
User Sohail Ashraf
by
5.3k points