Simple I/O problem can't get solved

nickgan.sps at windowslive.com nickgan.sps at windowslive.com
Fri Jun 21 05:20:25 EDT 2013


Τη Παρασκευή, 21 Ιουνίου 2013 12:15:59 μ.μ. UTC+3, ο χρήστης Peter Otten έγραψε:
> nickgan.sps at windowslive.com wrote:
> 
> 
> 
> > I have recently started to solve my first Python problems but I came
> 
> > across to this:
> 
> > Write a version of a palindrome recogniser that accepts a file name from
> 
> > the user, reads each line, and prints the line to the screen if it is a
> 
> > palindrome.(by http://www.ling.gu.se/~lager/python_exercises.html)
> 
> > 
> 
> > I think I coded it correctly but still I get no output. I do not have any
> 
> > errors I just do not get any output.
> 
> > 
> 
> > This is the code:
> 
> 
> 
> > import is_palindrome
> 
> > 
> 
> > filename = raw_input('Enter a file: ') # A text file
> 
> > f = open(filename)
> 
> > while True:
> 
> >         line = f.readline()
> 
> 
> 
> The line includes the trailing newline character which breaks the symmetry:
> 
> 
> 
> >>> "abba" == "abba"[::-1]
> 
> True
> 
> >>> "abba\n" == "abba\n"[::-1]
> 
> False
> 
> 
> 
> Use
> 
> 
> 
> word = line.strip()
> 
> 
> 
> to remove all leading and trailing whitespace.
> 
> 
> 
> >         if len(line) == 0:
> 
> >                 break
> 
> >         elif is_palindrome.is_palindrome(line): 
> 
> >                 print line,
> 
> > f.close()
> 
> 
> 
> Note that python allows you to iterate over the lines of a file with
> 
> 
> 
> for line in f:
> 
>     ...
> 
> 
> 
> Combining these modifications:
> 
> 
> 
> for line in f:
> 
>     word = line.strip()
> 
>     if is_palindrome.is_palindrome(word):
> 
>         print word

Thank you a lot it worked!



More information about the Python-list mailing list