slicing the end of a string in a list

Paul Rubin http
Thu Mar 2 23:10:41 EST 2006


John Salerno <johnjsal at NOSPAMgmail.com> writes:
> >   print [line[:-1] for line in open('C:\\switches.txt')]
> 
> Hmm, I just realized in my original code that I didn't escape the
> backslash. Why did it still work properly?

The character the backslash isn't special: \s doesn't get into
a code like \n, so the backslash is passed through.  Best not to
rely on that.

The preferred way to remove the newline is more like:
   for line in open('C:\\switches.txt'):
     print line.rstrip()

the rstrip method removes trailing whitespace, which might be \n
on some systems, \r\n on other systems, etc.

> And do I not need the 'r' parameter in the open function?

No you get 'r' by default.  If you want to write to the file you need
to pass the parameter.



More information about the Python-list mailing list