joeqesi
joeqesi

Reputation: 99

Editing strings in a list of lists

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', 'ipsum', 'dolor', 'sit', 'amet\n']
               ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis\n']]

I want to be able to move through the list of lists, and remove the '\n' from the last element of each list in the list of lists.

This is the script I wrote to try to do this, but it doesn't work because when I return n, it only returns the first element of the first list.

def remove_linebreaks(input):
for i in data:
    for n in i:
        if '\n' in n:
            n.strip('\n')
            return n
        else:
            return n
return input

Are there any other ways I could do this?

Upvotes: 1

Views: 128

Answers (5)

BigBrownBear00
BigBrownBear00

Reputation: 1480

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.

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

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

Upvotes: 1

gmfreak
gmfreak

Reputation: 399

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

"""

Upvotes: 0

BigBrownBear00
BigBrownBear00

Reputation: 1480

Why don't you just do return n.strip('\n')? You can get rid of the if/else

Upvotes: 1

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

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

Upvotes: 0

Related Questions