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?
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']]
example = [[x.replace('\r\n','') for x in i] for i in example]
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