Humberto Atondo Humberto Atondo - 25 days ago 9
Python Question

Python 3 palindromes in text file

with open('33.txt') as text:
for line in text:
line2 = line[:][::-1]
if line == line2:
print ('Palindrome!')


I am trying to check if the lines of text from a file are palindromes or not, but when I run the code it seems that is only checking if the last line is a palindrome. I want the code to check every line for palindromes, I have done similar programs but using string inside the code and I am using a similar approach but I don't know why it doesn't work.

Answer

The problem is that all the lines except last one have newline character at the end which needs to be removed. You can fix the issue with strip:

with open('33.txt') as text:
    for line in text:
        line = line.strip()
        line2 = line[::-1]
        if line == line2:
            print ('Palindrome!')