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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.