1

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

1
  • So its i[0] which ends in "K", so it must be: value=i[0].replace("K", "000") Commented Sep 2, 2022 at 7:43

2 Answers 2

1

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~']]
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome it works, thanks! Just some questions, why did you take lst[0][-1] and lst[0][:-1] ?
lst[0][-1] is the last character in the string. lst[0][:-1] is all characters in the string except the last one. Note: this code assumes that lst[0] refers to a non-empty string. Also, replace() is not used because consider what would happen if the string contained more than one 'K'
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.