Home > Enterprise >  How to replace a text in the nested list in Python
How to replace a text in the nested list in Python

Time:09-02

I am trying to replace an element in the nested list, but only the end part of the element

This is my nested list:

['715K', '2009-09-23', 'system.zip', ''],
 ['720M', '2019-09-23', 'sys2tem.zip~']]

And I want to replace "K" with "000" so it would look like this at the end:

 ['715000', '2009-09-23', 'system.zip', ''],
 ['720000', '2019-09-23', 'sys2tem.zip~']]

Separately it works, but I don"t know how to use index for the loop so that I could go through the nested list and change the text.

newList[0][0].replace("K", "000")  

I have tried this approach but it did not work:

rules={"K":"000", "M":"000000", "G":"000000000"}
new=[]
for item in newList[i]:
    if item[i][0].endswith("K"):
        value=item[i][0].replace("K", "000")
        new.append(value)

I have got the error "'list' object has no attribute 'replace'"

CodePudding user response:

You could use replace() but there's potential for ambiguity so try this:

nested_list = [['715K', '2009-09-23', 'system.zip', ''],
               ['720M', '2019-09-23', 'sys2tem.zip~']]

for lst in nested_list:
    if lst[0][-1] == 'K':
        lst[0] = lst[0][:-1] '000'

print(nested_list)

Output:

[['715000', '2009-09-23', 'system.zip', ''], ['720M', '2019-09-23', 'sys2tem.zip~']]

CodePudding user response:

You got that error because you are performing replace on the list object. the below solution is based on the fact that, we are sure we just have list inside a list...

def f(el):
    rules = {"K" : "000", "M":"000000", "G":"000000000"}
    if el and el[-1] in ["K", "M", "G"]:
        return el.replace(el[-1], rules.get(el[-1]))
    return el

new_list = [list(map(f, ll)) for ll in l]
print(new_list)
# [['715000', '2009-09-23', 'system.zip', ''], ['720000000', '2019-09-23', 'sys2tem.zip~']]

  • Related