Python strip with \n


Question

This is my problem.

I'm trying to read a text file and then convert the lines into floats. The text file has \n and \t in it though I don't know how to get rid of it.

I tried using line.strip() but it didn't take it off and I got an error when I wanted to convert the stuff to floats. I then tried line.strip("\n") but that didn't work either. My program works fine when I take out the \t and \n from the text file, but it's part of the assignment to get it to work with them.

I really don't know why this isn't working. Thanks for any help.

1
54
2/19/2012 8:07:48 PM

Accepted Answer

The clue is in the signature of rstrip.

It returns a copy of the string, but with the desired characters stripped, thus you'll need to assign line the new value:

line = line.rstrip('\n')

This allows for the sometimes very handy chaining of operations:

"a string".strip().upper()

As Max. S says in the comments, Python strings are immutable which means that any "mutating" operation will yield a mutated copy.

This is how it works in many frameworks and languages. If you really need to have a mutable string type (usually for performance reasons) there are string buffer classes.

22
5/23/2017 12:24:56 PM

you can do it like this

def add_quotes( fpath ):
        ifile = open( fpath, 'r' )
        ofile = open( 'ofile.txt', 'w' )
        for line in ifile:
            line=line.rstrip()
            convertedline = '"' + line + '", '
            ofile.write( convertedline + "\n" )
        ifile.close()
        ofile.close()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon