0

I have a long array that looks something like this :

arr=["5;V;K;4406632419324152;0123;172;9;0;0;06012020;3000"
"2;M;K;4406553211445698;0123;124;2;0;0;06012020;2000"
"3;M;K;5412115956124218;0123;236;3;0;1;06012020;2000"
"4;V;K;4406621015140546;0123;131;9;0;0;06012020;3000"]

Each index is a line from a text file. The content is not important, what is, however, is that I do not know length of the any index of array (meaning len(arr[i]) would be different for each index, the only way how I can be sure that I am accessing the "V" or "K" is by using split function)

arr[0].split(";")[1]

Is there a simple code that would replace the 6th elements (after split) in index to a new value?

What I am trying to achieve is to print

from

"5;V;K;4406632419324152;0123;172;9;0;0;06012020;3000"

to

"5;V;K;4406632419324152;0123;172;newValue;0;0;06012020;3000"

2
  • can't you read file as cvs file or something similar - ie. using pandas? Commented Jan 25, 2020 at 12:08
  • well it is unfortunately a highschool group project. We are only "allowed" or "adviced" to use pure tkinter. Even the file has to be a .txt Commented Jan 25, 2020 at 12:15

1 Answer 1

1

You can use a list comprehension with a ternary operator to replace the 6th element:

arr=["5;V;K;4406632419324152;0123;172;9;0;0;06012020;3000",
"2;M;K;4406553211445698;0123;124;2;0;0;06012020;2000",
"3;M;K;5412115956124218;0123;236;3;0;1;06012020;2000",
"4;V;K;4406621015140546;0123;131;9;0;0;06012020;3000"]
new_value = 4
arr[0] = ';'.join(v if i != 6 else str(new_value) for i, v in enumerate(arr[0].split(';')))
print(arr)

Output:

['5;V;K;4406632419324152;0123;172;4;0;0;06012020;3000', 
 '2;M;K;4406553211445698;0123;124;2;0;0;06012020;2000', 
 '3;M;K;5412115956124218;0123;236;3;0;1;06012020;2000', 
 '4;V;K;4406621015140546;0123;131;9;0;0;06012020;3000'
]
Sign up to request clarification or add additional context in comments.

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.