简体   繁体   English

在另一个字符串中匹配子字符串

[英]Matching substring in another string

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. 第二个列表包含要针对list1检查是否存在的目录。

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. 我想要的唯一结果是path/to/my/* ,但是当我使用str.find()它将返回包含pathtomy任何字符串,而不管它在字符串中的位置如何。

So instead of just getting: 因此,不仅仅是获得:

path/to/my/files
path/to/my/dirs

I get everything in list1 我把所有东西都放在list1

My code is like so: 我的代码是这样的:

for dir in list2:
   for path in list1:
      if path.find(dir):
         print(path)

All non-zero numbers are Truthy. 所有非零数字都是Truthy。 When your string is not found, .find() returns -1 which is still True . 当找不到您的字符串时, .find()返回-1 ,但仍为True You need to make sure the result is not -1 : 您需要确保结果不是-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. 正如@PadraicCunningham在评论中提到的那样,这不是最简单的方法。 Just use the in operator: 只需使用in运算符:

for dir in list2:
    for path in list1:
        if dir in path:
            print(path)

我认为您需要的是str.startswith()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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