Search code examples
pythonlistnested

How to replace a text in the nested list in Python


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'"


Solution

  • 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~']]