0

Below is the given list of strings from which I am trying to find the strings which contains the substring. Output is obtained perfectly without using functions. However when function is used, it does return only 1 substring and not the list of strings containing the substring.

L = ['dog', 'dodge', 'cat', 'cattle']

sub_string = str(input("Enter the substring: "))

for i in range(len(L)):
    v = L[i].find(sub_string, 0,100)
    if v >= 0:
        print(L[i])           #returns all the strings containing the substring very well.

def String_find(sub_string):
    for i in range(len(L)):
        if sub_string in L[i]:         
            return L[i]        #returns only 'dog' or 'cat' if substring is entered whereas 
                               #'dog','dodge' 
                               #or 'cat','cattle' is expected.

Total = String_find(sub_string)
#Output is obtained perfectly without using functions however when function is used it does return         
#only 1 substring and not the list of strings containing the substring.
3
  • 1
    return returns immediately, so the first match will trigger the exit of the function. You may be lookiing for yield, or to return a list that you fill with matches. Commented Mar 27, 2020 at 15:43
  • return will cause the loop to exit. So as soon as a match is found, it exits from the loop. Commented Mar 27, 2020 at 15:47
  • Thanks @L3viathan Commented Mar 27, 2020 at 15:51

1 Answer 1

3

You maybe want to do this:

def string_find(sub):
    return [item for item in L if sub in item]

items = string_find(sub_string)
print(items)
Sign up to request clarification or add additional context in comments.

1 Comment

Most optimal solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.