Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 ['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~']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading