Rief
Rief

Reputation: 451

Replace string in specific index in list of lists python

How can i replace a string in list of lists in python but i want to apply the changes only to the specific index and not affecting the other index, here some example:

mylist = [["test_one", "test_two"], ["test_one", "test_two"]]

i want to change the word "test" to "my" so the result would be only affecting the second index:

mylist = [["test_one", "my_two"], ["test_one", "my_two"]]

I can figure out how to change both of list but i can't figure out what I'm supposed to do if only change one specific index.

Upvotes: 1

Views: 1906

Answers (2)

Rusty Robot
Rusty Robot

Reputation: 1845

There is a way to do this on one line but it is not coming to me at the moment. Here is how to do it in two lines.

for two_word_list in mylist:
    two_word_list[1] = two_word_list.replace("test", "my")

Upvotes: 2

Chris
Chris

Reputation: 29742

Use indexing:

newlist = []
for l in mylist:
    l[1] = l[1].replace("test", "my")
    newlist.append(l)
print(newlist)

Or oneliner if you always have two elements in the sublist:

newlist = [[i, j.replace("test", "my")] for i, j in mylist]
print(newlist)

Output:

[['test_one', 'my_two'], ['test_one', 'my_two']]

Upvotes: 3

Related Questions