Tengansui Tengansui - 3 months ago 17
Python Question

python: if (substring X in string Y) only true for last characters?

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:

prediction:


  1. dog

  2. cat



actual:


  1. red,dog

  2. cat,blue



returns true then returns false

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


Edit: .rstrips works! The expected output is true, true

Answer

readlines gives you each line include the newline at the end of the line. So you're doing comparisons like "cat\n" in "cat,blue\n". Since there isn't a newline in the right place, the check fails.

Try this to strip the newlines off the end of each line:

with open("test_class.txt") as g:
    prediction = [line.rstrip() for line in g]

with open("y_smallTest.txt") as g:
    actual = [line.rstrip() for line in g]

for n in range(len(prediction)):
    if prediction[n] in actual[n]:
        correct += 1
    else:
        incorrect +=1

EDIT

Perhaps a better rewrite is to use zip and just iterate through the files:

with open("test_class.txt") as predictions, open("y_smallTest.txt") as actuals:
    for prediction, actual in zip(predictions, actual):
        if prediction.rstrip() in actual:
            correct += 1
        else:
            incorrect += 1
Comments