python: if (substring X in string Y) only true for last characters?
<p>This code only returns true when the substring is at the end. How do I fix it to consider any substring? Data looks like this:</p>

<p>prediction: </p>

<ol>
<li><p>dog</p></li>
<li><p>cat</p></li>
</ol>

<p>actual:     </p>

<ol>
<li><p>red,dog</p></li>
<li><p>cat,blue</p></li>
</ol>

<p>returns true then returns false</p>

<pre><code>with open("test_class.txt") as g:
    prediction = g.readlines()

with open("y_smallTest.txt") as g:
    actual = g.readlines()

for n in range(len(prediction)):
    if prediction[n] in actual[n]:
        correct += 1
    else:
        incorrect +=1
</code></pre>

<p>Edit: .rstrips works! The expected output is true, true</p>

<p>You just need to <em>rstrip</em> the <em>newline</em> from each line of the first file so you don't compare <code>dog\n</code> with <code>red,dog\n</code>, the newline on the string you are testing is irrelevant.  You can also use <em>zip</em> and read the files line by line withput the need for <em>readlines</em> and indexing:</p>

<pre><code>with open("test_class.txt") as f1, open("y_smallTest.txt") as f2:
    correct = incorrect = 0
    for a, b in zip(f1, f2):
        if a.rstrip() in b:
              correct += 1
        else:
             incorrect += 1
</code></pre>

<p>If you want exact matches then you will need to <em>rstrip</em> and <em>split</em> on the comma:</p>

<pre><code>with open("test_class.txt") as f1, open("y_smallTest.txt") as f2:
    correct = incorrect = 0
    for a, b in zip(f1, f2):
        if a.rstrip() in b.rstrip().split(","):
            correct += 1
        else:
            incorrect += 1
</code></pre>

<p>The difference on splitting would mean <em>dog</em> would not match <em>dogs,cats</em>.</p>

python python-3.x