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'
?
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.
With the data you have, just use split() (no args). It will strip the whitespace first, then split on whitespace.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With