How to remove \n from a list element?

Mr Wotan picture Mr Wotan · Oct 3, 2010 · Viewed 298.5k times · Source

I'm trying to get Python to a read line from a .txt file and write the elements of the first line into a list. The elements in the file were tab- separated so I used split("\t") to separate the elements. Because the .txt file has a lot of elements I saved the data found in each line into a separate list.

The problem I currently have is that it's showing each list like this:

['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']

How can I remove \n from the last element of the list and make it just '7.3'?

Answer

Bolo picture Bolo · Oct 3, 2010

If you want to remove \n from the last element only, use this:

t[-1] = t[-1].strip()

If you want to remove \n from all the elements, use this:

t = map(lambda s: s.strip(), t)

You might also consider removing \n before splitting the line:

line = line.strip()
# split line...