-1

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
Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37

1 Answers1

2

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 :)

  • Thank You It worked. From next time i will surely provide with the file. – Chitransh Mathur Dec 09 '19 at 15:46
  • 1
    It isn't yet :) to do so (if you want to, of course, but since you're new I'm showing you around) you can click on the checkmark under the answer score. see [an image here](https://images.app.goo.gl/k6oWNNoRuWjyqrQW6) and [the official doc](https://stackoverflow.com/help/someone-answers). Both of us will win some reputation, and future users are more likely to search for an answer in this post – Grégoire Roussel Dec 10 '19 at 08:32