Reputation: 6391
I have two lists that contain strings. The first list contains a list of files and directories:
list1 = ['path/to/my/files',
'path/to/more/of/my/files',
'path/to/my/dirs',
'path/to/more/of/mydirs']
The second list contains dirs that I want to check against list1
for existence.
list2 = ['path/to/my',
'random/path/to/somewhere',
'path/does/not/matter',
'hey/path/is/here']
The only results I want is path/to/my/*
, but when I use str.find()
it is returning any string that contains path
or to
or my
regardless of where it occurs in the string.
So instead of just getting:
path/to/my/files
path/to/my/dirs
I get everything in list1
My code is like so:
for dir in list2:
for path in list1:
if path.find(dir):
print(path)
Upvotes: 0
Views: 58
Reputation: 20336
All non-zero numbers are Truthy. When your string is not found, .find()
returns -1
which is still True
. You need to make sure the result is not -1
:
for dir in list2:
for path in list1:
if path.find(dir) != -1:
print(path)
As @PadraicCunningham mentioned in a comment, that isn't the easiest way. Just use the in
operator:
for dir in list2:
for path in list1:
if dir in path:
print(path)
Upvotes: 3