[英]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. 一切正常,除了在包含目录的字符串中查找Sample_8_1时,if条件还接受名称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? 如何使它完全匹配,以防止多次进入同一目录?
You could try searching for sample_8_1/
(ie, include the following slash). 您可以尝试搜索sample_8_1/
(即,包括以下斜杠)。 I guess given your code that would be dire.find(name+'/')
. 我想给你的代码将是dire.find(name+'/')
。 This just a quick and dirty approach. 这只是一种快速而肮脏的方法。
Assuming that dire
is populated with absolute path names 假设用绝对路径名填充了dire
for name in sample_names:
if name in dire:
...
eg 例如
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.