Python - file lines - pallindrome
<p>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:</p>

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

<p>But if I print like this, without an if condition, it prints the words:</p>

<pre><code>with open("words.txt") as f:
    for line in f:
        print line
</code></pre>

<p>I wonder why It wont print the words that I've written in the file:</p>

<pre><code>sefes
kurwa
rawuk
lol
bollob
</code></pre>

<p>When you read a line from a file like this, you also get the newline character. So, e.g., you're seeing <code>'sefes\n'</code>, which when reversed is <code>'\nsefes'</code>. These two lines are of course not equal. One way to solve this is to use <code>rstrip</code> to remove these newlines:</p>

<pre><code>with open("words.txt") as f:
    for line in f:
        line = line.rstrip()
        if line == line[::-1]:
            print line
</code></pre>

python python-2.7 palindrome