Im trying to print palindrome words in a file (where each line is a word) in python. Thats what I have so far: I have to work in Unix so I wrote my script in file palindrome.py as below:
#!/usr/bin/python
def isPalindrome(a):
if a == a[::-1]:
print a
with open ('fileName') as f:
for line in f:
isPalindrome(line)
When I run the file it doesn't print anything even-though there are palindrome words in my file. I think the problem is related to my function call because if instead of isPalindrome(line) I have isPalindrome('aha') it will print aha. I tried to print each line after the for loop but that works as well. It does print all the lines of the file. So line does get different values so I guess there might be something related to the call but I am failing to find out what.
2 Answers 2
You need to strip newlines from the end of your lines. Try call as isPalindrome(line.strip()).
Attention: file.readlines() does not wrap end line characters!!
so if in you file you have aha in one line, the line will be aha\n (with the new line char...)...
I suggest use of replace() string method.
Your code:
#!/usr/bin/python
def isPalindrome(a):
if a == a[::-1]:
print a
with open ('fileName') as f:
for line in f:
isPalindrome(line.replace('\n', '').replace("\r", "")) # replace carriage return / line feed chars