3

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.

Benjamin Hodgson
45k18 gold badges115 silver badges169 bronze badges
asked Apr 16, 2016 at 17:00
0

2 Answers 2

6

You need to strip newlines from the end of your lines. Try call as isPalindrome(line.strip()).

Benjamin Hodgson
45k18 gold badges115 silver badges169 bronze badges
answered Apr 16, 2016 at 17:03
Sign up to request clarification or add additional context in comments.

2 Comments

Might also be useful to ignore case differences.
Thanks for your help.
1

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
answered Apr 16, 2016 at 17:04

2 Comments

Thank you. It worked with the file.readlines() as well but I will need to find the words length as well so this was helpful.
len(word) . to get the length of a string

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.