0

我试图在一个字符串中找到一个子字符串,但我没有达到我想要的结果。

我有几个字符串包含指向不同目录的方向:

'/Users/mymac/Desktop/test_python/result_files_Sample_8_11/logs', 
'/Users/mymac/Desktop/test_python/result_files_Sample_8_1/logs', 
'/Users/mymac/Desktop/test_python/result_files_Sample_8_9/logs'

这是我的代码的一部分,我试图找到与子字符串完全匹配的部分:

 for name in sample_names:

        if (dire.find(name)!=-1): 

            for files in os.walk(dire):

                for file in files:
                    list_files=[]
                    list_files.append(file)
                    file_dict[name]=list_files

一切正常,除了在包含目录的字符串中查找 Sample_8_1 时,if 条件也接受名称 Sample_8_11。我怎样才能使它完全匹配以防止多次进入同一目录?

4

2 回答 2

2

您可以尝试搜索sample_8_1/(即包括以下斜杠)。我猜你的代码是dire.find(name+'/'). 这只是一种快速而肮脏的方法。

于 2012-06-08T08:15:13.860 回答
1

假设dire用绝对路径名填充

for name in sample_names:
    if name in dire:
        ...

例如

samples = ['/home/msvalkon/work/tmp_1',
           '/home/msvalkon/work/tmp_11']

dirs = ['/home/msvalkon/work/tmp_11']

for name in samples:
    if name in dirs:
        print "Entry %s matches" % name

Entry /home/msvalkon/work/tmp_11 matches 
于 2012-06-08T08:20:53.780 回答