Search code examples
pythonpalindrome

Dealing with trailing newline when checking for palindromes


I was trying to import a palindrome function from a previously made code. Initially the palindrome code was working properly, but after I imported it, it is not showing correct answer.

import re
def check(string):
    if (string==string[::-1]):
        print ("{} is palindorme".format(string))
    else:
        print ("{} is not palindorme".format(string))



def palindrome(text):
    c=re.sub('["?",",",".","/","@","#","%","&","*","!"," "]',"",text)
    check(c)         

This is the function I am using:

from pal_func import palindrome
f=open("C:\\Users\\hp\\Desktop\\test file.txt",'r')
c=f.readline().lower()
print(c)
palindrome(c)

Output should be:

was it a cat i saw?
wasitacatisaw is palindrome

But it is showing:

was it a cat i saw?

wasitacatisaw

 is not palindorme

Solution

  • In brief

    Strip the trailing newline with:

    c=f.readline().lower().strip()
    

    In details

    Your problem does not seem to come from the code, but from the way you read your file.

    The function readline reads a line from the file but will not strip the trailing newline. The hint was that the answer

    wasitacatisaw
     is not palindrom
    

    has a newline you didn't write yourself

    So the function check get the string wasitacatisaw<newline>, which is not a palindrom.

    Last word : the next time, please also provide the file you're dealing with (without any personal infos nor passwords, of course), so that SO user can reproduce the error :)