 <p><strong>Method 1:</strong> Using <code>list.index</code>:</p> <pre><code>def match(strs, actual): seen = {} act = actual.split('/') for x in strs.split('/'): if x in seen: #if the item was already seen, so start search #after the previous matched index ind = act.index(x, seen[x]+1) yield ind seen[x] = ind else: ind = act.index(x) yield ind seen[x] = ind ... &gt;&gt;&gt; p1 = '/foo/baz/myfile.txt' &gt;&gt;&gt; p2 = '/bar/foo/myfile.txt' &gt;&gt;&gt; actual = '/foo/bar/baz/myfile.txt' &gt;&gt;&gt; list(match(p1, actual)) #ordered list, so matched [0, 1, 3, 4] &gt;&gt;&gt; list(match(p2, actual)) #unordered list, not matched [0, 2, 1, 4] &gt;&gt;&gt; p1 = '/foo/bar/bar/myfile.txt' &gt;&gt;&gt; p2 = '/bar/bar/baz/myfile.txt' &gt;&gt;&gt; actual = '/foo/bar/baz/bar/myfile.txt' &gt;&gt;&gt; list(match(p1, actual)) #ordered list, so matched [0, 1, 2, 4, 5] &gt;&gt;&gt; list(match(p2, actual)) #unordered list, not matched [0, 2, 4, 3, 5] </code></pre> <hr> <p><strong>Method 2:</strong> Using <code>defaultdict</code> and <code>deque</code>:</p> <pre><code>from collections import defaultdict, deque def match(strs, actual): indexes_act = defaultdict(deque) for i, k in enumerate(actual.split('/')): indexes_act[k].append(i) prev = float('-inf') for item in strs.split('/'): ind = indexes_act[item][0] indexes_act[item].popleft() if ind &gt; prev: yield ind else: raise ValueError("Invalid string") prev = ind </code></pre> <p><strong>Demo:</strong></p> <pre><code>&gt;&gt;&gt; p1 = '/foo/baz/myfile.txt' &gt;&gt;&gt; p2 = '/bar/foo/myfile.txt' &gt;&gt;&gt; actual = '/foo/bar/baz/myfile.txt' &gt;&gt;&gt; list(match(p1, actual)) [0, 1, 3, 4] &gt;&gt;&gt; list(match(p2, actual)) ... raise ValueError("Invalid string") ValueError: Invalid string &gt;&gt;&gt; p1 = '/foo/bar/bar/myfile.txt' &gt;&gt;&gt; p2 = '/bar/bar/baz/myfile.txt' &gt;&gt;&gt; actual = '/foo/bar/baz/bar/myfile.txt' &gt;&gt;&gt; list(match(p1, actual)) [0, 1, 2, 4, 5] &gt;&gt;&gt; list(match(p2, actual)) ... raise ValueError("Invalid string") ValueError: Invalid string </code></pre>