Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a string in list of lists

I have a list of lists of strings like:

example = [["string 1", "a\r\ntest string:"],["string 1", "test 2: another\r\ntest string"]]

I'd like to replace the "\r\n" with a space (and strip off the ":" at the end for all the strings).

For a normal list I would use list comprehension to strip or replace an item like

example = [x.replace('\r\n','') for x in example]

or even a lambda function

map(lambda x: str.replace(x, '\r\n', ''),example)

but I can't get it to work for a nested list. Any suggestions?

like image 838
user1888390 Avatar asked Dec 08 '12 20:12

user1888390


2 Answers

Well, think about what your original code is doing:

example = [x.replace('\r\n','') for x in example]

You're using the .replace() method on each element of the list as though it were a string. But each element of this list is another list! You don't want to call .replace() on the child list, you want to call it on each of its contents.

For a nested list, use nested list comprehensions!

example = [["string 1", "a\r\ntest string:"],["string 1", "test 2: another\r\ntest string"]]
example = [[x.replace('\r\n','') for x in l] for l in example]
print example

[['string 1', 'atest string:'], ['string 1', 'test 2: anothertest string']]
like image 140
Io_ Avatar answered Oct 03 '22 18:10

Io_


example = [[x.replace('\r\n','') for x in i] for i in example]
like image 23
sions Avatar answered Oct 03 '22 17:10

sions