Skip to content Skip to sidebar Skip to footer

How To Check For Part Of A String Within A List?

What is the most efficient way to check for part of a string within a list? For example, say I am looking for '4110964_se' (True) or '4210911_sw' (False) in the following list: fil

Solution 1:

any('4110964_se'in f for f in files) # check if the string is in any of the list items

Solution 2:

Malik Brahimi's answer works, though another way of doing this is just to put the files in a for loop like this:

for f in files:
    print"4110964_se"in f

The reason your solution doesn't work is because it only looks for items that have the exact value "4110964_se", rather than looking in each string to see if that value is anywhere in any of the strings. For example, if you did:

print "H:\\co_1m_2013\\41108\\m_4110864_se_12_1_20130717.tif"in files

It would print True, because you gave it the full file name, rather than just a piece of it

Solution 3:

You can use:

for x in files:
    if'4110964_se'in x:
        bool('4110964_se')

It prints:

True

Post a Comment for "How To Check For Part Of A String Within A List?"