Leo.peis
Leo.peis

Reputation: 14353

Exact match in strings in python

I am trying to find a sub-string in a string, but I am not achieving the results I want.

I have several strings that contains the direction to different directories:

'/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'

Here is the part of my code here I am trying to find the exact match to the sub-string:

 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

Everything works fine except that when it looks for Sample_8_1 in the string that contains the directory, the if condition also accepts the name Sample_8_11. How can I make it so that it makes an exact match to prevent from entering the same directory more than once?

Upvotes: 0

Views: 1064

Answers (2)

msvalkon
msvalkon

Reputation: 12077

Assuming that dire is populated with absolute path names

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

e.g.

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 

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251598

You could try searching for sample_8_1/ (i.e., include the following slash). I guess given your code that would be dire.find(name+'/'). This just a quick and dirty approach.

Upvotes: 2

Related Questions