[英]Exact match in strings in python
我试图在字符串中找到一个子字符串,但没有达到我想要的结果。
我有几个字符串,其中包含指向不同目录的方向:
'/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。 如何使它完全匹配,以防止多次进入同一目录?
您可以尝试搜索sample_8_1/
(即,包括以下斜杠)。 我想给你的代码将是dire.find(name+'/')
。 这只是一种快速而肮脏的方法。
假设用绝对路径名填充了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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.