0

First, I have a file named "words.txt" with several words(apple noon tea water). and I want to make some code to check if there is a word that is a palindrome(noon).

my code is:

with open('words.txt','r') as file:
    line = None
    while line !='':
        line = file.readline()
        
        if line == line[::-1]:
            print(line.strip('\n'))

        else :
            pass

but code doesn't work as my intent, It looks like If condition is being ignored

I don'n know why this happens. I need your help Thx

s9e5on
  • 11
  • 1
  • 4
  • 3
    The condition `line == line[::-1]` won't be `True` in general, because `line` has `'\n'` at the end. Instead, try `line = file.readline().rstrip('\n')`. – j1-lee Jan 27 '22 at 01:58
  • 1
    oh I figured out why, and fixed the code. thanks for the help – s9e5on Jan 27 '22 at 02:03

0 Answers0