I am reading a file that has list. Below is the input file.
[1,2,3,4]
[42]
[1,1,2,3,5,8]
[]
Now as you can see there are lists which is read as string character and I am trying to convert it into an actual list. Below is the code I'm using.
_list = list(sys.stdin.readline().strip())
_final_list = []
for n in _list:
try:
n = int(n)
except ValueError:
continue
if isinstance(n, int):
_final_list.append(n)
Now my code works fine until a number is more than one digit. For example 42 would become 4, 2. Which is not what I want.
My code generates below result.
[1, 2, 3, 4]
[4, 2] <--- FALSE
[1, 1, 2, 3, 5, 8]
[]
What should I do here to accomplish this task without using libraries such as ast
ast? Why are you doing this in the first place? Why not use a built in serialization method likejsonorpickle?