I\'ve made a list of lists from a text block where each list contains all the words in a line as a separate element, like this:
listoflists = [[\'Lorem\', \'ipsu
Why don't you just do return n.strip('\n')
? You can get rid of the if/else
listoflists = [['Lorem', 'ipsum', 'dolor', 'sit', 'amet\n'],['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis\n']]
for l in listoflists:
l[-1] = l[-1].replace('\n','')
print listoflists
""" Output:
[['Lorem', 'ipsum', 'dolor', 'sit', 'amet'], ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis']]
"""
Also, the reason your original code does not work is b/c n.strip('\n')
does not change the value of n
. It returns a new string. If you did something like n=n.strip('\n'); return n
, that would work.
Just iterate over each list and replace the last element with the last element with the '\n'
stripped.
>>> listoflists = [['Lorem', 'ipsum', 'dolor', 'sit', 'amet\n'],
['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis\n']]
>>> for elem in listoflists:
elem[-1] = elem[-1].strip('\n')
>>> listoflists
[['Lorem', 'ipsum', 'dolor', 'sit', 'amet'], ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis']]
EDIT - Since in the code, you seem to be stripping \n
from each element you could do
>>> [[elem.strip('\n') for elem in lst] for lst in listoflists]
[['Lorem', 'ipsum', 'dolor', 'sit', 'amet'], ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis']]
You could use a list comprehension
listoflists = [['Lorem', 'ipsum', 'dolor', 'sit', 'amet\n'],
['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis\n']]
[[j.replace("\n","") for j in i] for i in listoflists]
Output
[['Lorem', 'ipsum', 'dolor', 'sit', 'amet'],
['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis']]