You want to determine if the list containing the string contains a specific string

Asked 1 years ago, Updated 1 years ago, 80 views

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

How do I find out if there is an 'abc' in the list from the same list?

What I know is that list items like 'abc-123' and 'abc-456' have to match exactly 'abc' so it can't ㅜ<

if 'abc' in my_list:

python find substring

2022-09-22 16:14

1 Answers

In this case, instead of checking that there is 'abc' in the list (if 'abc' in my_list), you should check that there is 'abc' in each of the list items.

some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

#If you write it long,
for s in some_list:
    if "abc" in s:
        print ("Yes")
        Break; # If I find one, I won't find the back


#If you write it short,
if any("abc" in s for s in some_list):
    print ("Yes")
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

#If you write it long,
resultlist = []
for s in some_list:
    if "abc" in s:
        resultlist.append(s)

#If you write it short,
matching = [s for s in some_list if "abc" in s] 


2022-09-22 16:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.