简体   繁体   中英

How to test if a string is partialy contained in a list in Python

I have the list:

list1 = ['tom.frank.phillips','jimmy.fund.roberts','markus.shane.sherman','glen.carl.smith']

I am trying to test if the following names are contained anywhere in this list:

nameslist = ['shane', 'frank', 'dale', 'roberts', 'smith', 'tony']

If they are not contained anywhere in the original list, then I want to print the name.

I have tried:

for name in nameslist:
    if name not in list1:
        print(name)

But when I do this, all of the names get printed.

None of those names is an element of list1 . You need to check to see whether the name is a sub-string of any element of list1 .

if not any(name in full_name for full_name in list1):
    print(name)

Another way is to simply concatenate all of your long names; then use in on that single string:

all_names = ' '.join(list1)
for name in names list:
    if not name in all_names:
        print(name)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM