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?

Io_
  • 183
  • 7
user1888390
  • 91
  • 1
  • 1
  • 2

7 Answers7

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']]
Io_
  • 183
  • 7
  • 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] – user1888390 Dec 08 '12 at 21:34
  • What if I don't know how much nested is that list and I want to replace in the whole? – Peter.k Nov 21 '17 at 14:04
4
example = [[x.replace('\r\n','') for x in i] for i in example]
sions
  • 107
  • 1
  • 7
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)
Stuart
  • 9,597
  • 1
  • 21
  • 30
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']
Estatistics
  • 874
  • 9
  • 24
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 :)

JAL IPO_
  • 56
  • 1
  • 6
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']]
Kayvan Shah
  • 375
  • 2
  • 11
-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!

  • 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](/help/how-to-answer). – Community Dec 14 '22 at 15:49