Idontreallywolf Idontreallywolf - 3 months ago 18
Python Question

Python - file lines - pallindrome

I have been doing python tasks for learning and I came across this task where I have to read a file that includes few words and if a line is palindrome (same when written backwards: lol > lol)
so I tried with this code but It doesn't print anything on the terminal:

with open("words.txt") as f:
for line in f:
if line == line[::-1]:
print line


But if I print like this, without an if condition, it prints the words:

with open("words.txt") as f:
for line in f:
print line


I wonder why It wont print the words that I've written in the file:

sefes
kurwa
rawuk
lol
bollob

Answer

This is because those lines contain "\n" on the end. "\n" means new line. Therefore none of those are palindromes according to python.

You can strip off the "\n" first by doing:

with open("words.txt") as f:
    for line in f:
        if line.strip() == line.strip()[::-1]:
            print line