Replace a string in list of lists
Asked Answered
M

7

9

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?

Monarski answered 8/12, 2012 at 20:51 Comment(0)
M
18

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']]
Markswoman answered 8/12, 2012 at 20:54 Comment(2)
Thanks, I'm just starting out on learning python, but couldn't find a decent example anywhere. I managed to get it to work in my program. I saw that I was trying to call example twice like: for x in example] for l in example]Monarski
What if I don't know how much nested is that list and I want to replace in the whole?Pursuant
T
4
example = [[x.replace('\r\n','') for x in i] for i in example]
Tacet answered 8/12, 2012 at 20:54 Comment(1)
It would be great to have an explanation of what's going on.Sb
S
3

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)
Shelba answered 8/12, 2012 at 22:46 Comment(0)
C
1

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']
Canuck answered 29/4, 2016 at 12:53 Comment(0)
P
0

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 :)

Pretended answered 9/1, 2023 at 10:19 Comment(0)
S
0

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']]
Sancha answered 16/4, 2023 at 9:52 Comment(0)
O
-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!

Ormazd answered 10/12, 2022 at 19:7 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Multiplier

© 2022 - 2024 — McMap. All rights reserved.