Replace a string in list of lists

user1888390 picture user1888390 · Dec 8, 2012 · Viewed 11.1k times · Source

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?

Answer

Io_ picture Io_ · Dec 8, 2012

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