Reputation: 91
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?
Upvotes: 9
Views: 17855
Reputation: 508
Here's am implementation with recusion and generators
def replace_nested(lst, old_str, new_str):
for item in lst:
if isinstance(item, list):
yield list(replace_nested(item, old_str, new_str))
else:
yield item.replace(old_str, new_str).rstrip(':')
example = [
["string 1", "a\r\ntest string:"],
["string 1", "test 2: another\r\ntest string"]
]
new_example = list(replace_nested(example, '\r\n', ' '))
print(new_example)
Output
[['string 1', 'a test string'], ['string 1', 'test 2: another test string']]
Upvotes: 0
Reputation: 9858
In case your lists get more complicated than the one you gave as an example, for instance if they had three layers of nesting, the following would go through the list and all its sub-lists replacing the \r\n with space in any string it comes across.
def replace_chars(s):
return s.replace('\r\n', ' ')
def recursive_map(function, arg):
return [(recursive_map(function, item) if type(item) is list else function(item))
for item in arg]
example = [[["dsfasdf", "another\r\ntest extra embedded"],
"ans a \r\n string here"],
['another \r\nlist'], "and \r\n another string"]
print recursive_map(replace_chars, example)
Upvotes: 3
Reputation: 1
For beginners looking!
Change hello to 'goodbye'.
step 1: index first
list3 = [1,2,[3,4,'hello']]
index=0 1 2
then you are on to the second list in which it starts back at zero. the list is index 2 as a whole so when referring to index 2 it means you are at [3,4,'hello']
step 2 figure out the hello index
list3 = [1,2,[3,4,'hello']]
index= 0 1 2
since you start at 0 again, you go from 0 until you get the number or string you want to change. you can also do -1 because hello is the last index of the list
list3[2][2] = 'goodbye'
result = [1,2,[3,4,'goodbye']]
i hope this clears things up!
Upvotes: -1
Reputation: 106
you can easily do it by the code below
example = [["string 1", "a\r\ntest string:"],["string 1", "test 2: another\r\ntest string"]]
example_replaced = []
def replace(n):
new = n.replace("\r\n" , " ")
if new[:-1] == ":" : new = new[:-1]
return new
for item in example:
Replaced = [replace(sub_item) for sub_item in item]
example_replaced.append(Replaced)
print(example_replaced)
the output will be:
[['string 1', 'a test string:'], ['string 1', 'test 2: another test string']]
enjoy :)
Upvotes: 0
Reputation: 940
The following example, iterate between lists of lists (sublists), in order to replace a string, a word.
myoldlist=[['aa bbbbb'],['dd myword'],['aa myword']]
mynewlist=[]
for i in xrange(0,3,1):
mynewlist.append([x.replace('myword', 'new_word') for x in myoldlist[i]])
print mynewlist
# ['aa bbbbb'],['dd new_word'],['aa new_word']
Upvotes: 1
Reputation: 183
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']]
Upvotes: 18