Simple I/O problem can't get solved

Peter Otten __peter__ at web.de
Sat Jun 22 06:11:45 EDT 2013


Chris Angelico wrote:

> On Fri, Jun 21, 2013 at 7:15 PM, Peter Otten <__peter__ at web.de> wrote:
>> Combining these modifications:
>>
>> for line in f:
>>     word = line.strip()
>>     if is_palindrome.is_palindrome(word):
>>         print word
> 
> Minor quibble: I wouldn't use the name 'word' here, unless you're
> expecting the file to consist of one-word lines (such as DICTOT.DIC
> from old PMMail). For detecting phrase/sentence palindromes, I'd keep
> the name 'line'.

Somehow it didn't occur to me that you might test anything but words.
However, if you want to check sentences (as some unused code in the original 
post suggests) I think you should not strip off the newline and leave the 
necessary cleanup to the test function:

>>> def is_palindrome(s):
...     t = "".join(c for c in s.casefold() if c.isalnum())
...     return t == t[::-1]
... 
>>> is_palindrome("A man, a plan, a canal - Panama!\n")
True





More information about the Python-list mailing list