how to delete "\n"

Jia Hu hujia06 at gmail.com
Mon Jul 12 17:33:02 EDT 2010


Thank you. It works now.

 if I use 'print' to print the whole list, 'print' will add newline
at the end of the list but not each item in the list.  right?

For the code:
for line in fileName:
    line = line.rstrip('\n')
I think this will affect 'fileName' because it assign the value to 'line' ?
But when I print fileName, "\n" still exists at each item in the list.

Because each line in my txt file are numeric values. is there any other
better way to get each
numerical value at each line? for example using numpy or changing string
list to numerical list?

Thank you for help.

On Mon, Jul 12, 2010 at 4:45 PM, Chris Rebert <clp2 at rebertia.com> wrote:

> On Mon, Jul 12, 2010 at 1:27 PM, Jia Hu <hujia06 at gmail.com> wrote:
>  > Hi, I just want to delete "\n" at each line. My operating system is
> ubuntu
> > 9.1. The code is as follows
> >
> > #!/usr/bin/python
> > import string
> > fileName=open('Direct_Irr.txt', 'r') # read file
> > directIrr = fileName.readlines()
> > fileName.close()
> > for line in directIrr:
> >        line.rstrip('\n')
> > print directIrr
> >
> > But I found there is still "\n" . Could someone help me why it is not
> > correct?
>
> .rstrip() returns a *new* string without trailing whitespace (which
> you are currently then throwing away); it does *not* modify string
> objects in-place. Python strings objects are entirely immutable and
> unmodifiable; all operations on them merely produce /new/ strings.
>
> Assuming you still want to use .readlines(), you'd do:
> directIrr = fileName.readlines()
> fileName.close()
> directIrr = [line.rstrip('\n') for line in directIrr]
> print directIrr
>
> For how third line works, google "python list comprehensions".
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100712/21603b3b/attachment-0001.html>


More information about the Python-list mailing list