Idont Reallywolf Idont Reallywolf - 1 year ago 42
Python Question

Python - Readline and compare

Im trying to create a function which reads each line in a file and compares the words with their reverse (palindrome) version

i.e > (heheh = heheh) & (law = wal)
. So when i tried to do that the condition has failed and the function returned an empty list.


def palindrome_lst():
lst = []
with open("words.txt", "r") as f:
for line in f:
if line == line[::-1]:
return lst

print palindrome_lst()


When iterating over the lines in a file, you're getting the line-terminator along with the rest of the line. Id est, you're not comparing "eye" == "eye", but "eye\n" == "\neye", which is of course false for all words.

Try adding line = line.strip() before the comparison.