Idont Reallywolf Idont Reallywolf - 5 months ago 8
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.

CODE

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

print palindrome_lst()

Answer

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.

Comments