Check if a string contains all words of another string in the same order python?
<p>I want to check if a string contains all of the substring's words and retains their order; at the moment I am using the following code; However it is very basic, seems inefficient and likely there is a much better way of doing it. I'd really appreciate if you could tell me what a more efficient solution would be. Sorry for a noob question, I am new to the programming and wasn't able to find a good solution</p>

<pre><code>def check(main, sub_split):
    n=0
    while n &lt; len(sub_split):
        result = True
        if sub_split[n] in main:
            the_start =  main.find(sub_split[n])
            main = main[the_start:]

        else:
            result=False
        n += 1
    return result

a = "I believe that the biggest castle in the world is Prague Castle "
b= "the biggest castle".split(' ')

print check(a, b)
</code></pre>

<p>update: interesting; First of all thank you all for your answers. Also thank you for pointing out some of the spots that my code missed. I have been trying different solutions posted here and in the links, I will add update how they compare and accept the answer then.</p>

<p><strong>update:</strong>
Again thank you all for great solutions, every one of them had major improvements compared to my code; I checked the suggestions with my requirements for 100000 checks and got the following results;
suggestions by:
Padraic Cunningham - consistently under 0.4 secs (though gives some false positives when searching for only full words;
galaxyan - 0.65 secs; 0.75 secs
friendly dog - 0.70 secs
John1024 - 1.3 secs (Highly accurate, but seems to take extra time)</p>

<p>if you just want to check whether there is a word contain in other string, no need to check all. You just need to find one and return true.<br>
when you check the item set is faster O(1)(average)</p>

<pre><code>a = "I believe that the biggest castle in the world is Prague Castle "
b = "the biggest castle"

def check(a,b):
    setA,lstB = set( a.split() ), b.split() 
    if len(setA) &lt; len(lstB): return False 
    for item in lstB:
        if item in setA:
            return True
    return False

print check(a,b)
</code></pre>

<p>if you donot care the speed</p>

<pre><code>def check(a,b):
    setA,lstB = set( a.split() ), b.split() 
    return len(setA) &gt;= len(lstB) and any( 1 for item in lstB if item in setA) 
</code></pre>

<p>for speed and time complexity: <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">link</a></p>

python string python-2.7 substring