Python strip with \n

Mallard Duck picture Mallard Duck · Feb 19, 2012 · Viewed 495.3k times · Source

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.

Answer

austin1howard picture austin1howard · Feb 19, 2012

You should be able to use line.strip('\n') and line.strip('\t'). But these don't modify the line variable...they just return the string with the \n and \t stripped. So you'll have to do something like

line = line.strip('\n')
line = line.strip('\t')

That should work for removing from the start and end. If you have \n and \t in the middle of the string, you need to do

line = line.replace('\n','')
line = line.replace('\t','')

to replace the \n and \t with nothingness.