-1

how do you convert this string array '[1, 2, 3]' to an interger array

ok so this is not my real code but the part thats breaking

totalammount  = [1,2,3]

file = open("save", "w")
file.write(str(totalammount))
file = open("save", "r")
saveditems = file.read()
print(int(saveditems))

but if i run this it will say: ValueError: could not convert string to float: '[1, 2, 3]'

expected output: [1, 2, 3], so i can take out the numbers in the array

saveditems[0]

can anyone help me?

  • What should the output look like? can you give an example? You probably will have to iterate over `totalAmount`. Converting it to a string is hardly ever the correct thing to do (but very useful wenn debugging) – Ronald Jun 30 '21 at 12:53
  • 2
    Use a proper serialization format instead of just calling `str` on the value. In this case, JSON will do the job nicely (and give identical output in this particular case). – Thomas Jun 30 '21 at 12:54
  • 1
    I think your question can be boiled down to why does this error `print(float('[1,2,3]'))` ? And the answer is because you ask for the string to be converted into a single float value, which isn't possible. You need to parse the string and convert it to a list, then convert each element in the list. See Thomas' response for making this easy for yourself. – JeffUK Jun 30 '21 at 12:57

1 Answers1

0

Using eval() function

>>> t = '[1, 2, 3]'
>>> a = eval(t)
>>> a
[1, 2, 3]

but, as suggested in the comments, use json format. ('save' file contains [1,2,3])

>>> f = open("save", "r")
>>> myvalue = json.load(f)
>>> myvalue
[1, 2, 3]
>>> 
Yuri
  • 511
  • 3
  • 6