Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove \n from a list element?

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'?

like image 295
Mr Wotan Avatar asked Oct 03 '10 11:10

Mr Wotan


People also ask

How do you remove \n in Python?

Remove \n From the String in Python Using the str. strip() Method. In order to remove \n from the string using the str. strip() method, we need to pass \n and \t to the method, and it will return the copy of the original string after removing \n and \t from the string.

How do you remove n from a list in Python 3?

With the data you have, just use split() (no args). It will strip the whitespace first, then split on whitespace.

How do you remove a character from an element in a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.

How do you remove lines from a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.


1 Answers

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... 
like image 56
Bolo Avatar answered Sep 30 '22 18:09

Bolo