-1

I tried converting an array that is in a string string = "[[(34, 66, 75), (3, 145, 74)], [(5, 78, 33), (7, 44, 6)]]" to a working array [[(34, 66, 75), (3, 145, 74)], [(5, 78, 33), (7, 44, 6)]] in python but I failed. I tried so much but I couldn't think of another solution.

string = "[[(34, 66, 75), (3, 145, 74)], [(5, 78, 33), (7, 44, 6)]]"

arr = r"%s" %string

print(arr[1][0])

# output: (5, 78, 33)

I was hoping that if I manage to make the string raw I will be able to use the array in it.

Levi
  • 11
  • 2
  • 3
    `ast.literal_eval` is what you need - https://docs.python.org/3/library/ast.html#ast.literal_eval – slothrop Apr 22 '23 at 17:06
  • 2
    @slothrop or if it's valid JSON, you can also use [**`json.loads`**](https://docs.python.org/3/library/json.html#json.loads) – Peter Wood Apr 22 '23 at 17:13

1 Answers1

2

You can simply use ast.literal_eval like this,

import ast
string = "[[(34, 66, 75), (3, 145, 74)], [(5, 78, 33), (7, 44, 6)]]"
arr = ast.literal_eval(string)

print(arr)
print(arr[1][0])

Output:

[[(34, 66, 75), (3, 145, 74)], [(5, 78, 33), (7, 44, 6)]]
(5, 78, 33)
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103