Reputation: 11
to convert <class 'bytes'> data in tuple in python? example:
data = b'["1","2","3"]'
data = tuple(data)
print(data)
output:(91, 34, 49, 34, 44, 34, 50, 34, 44, 34, 51, 34, 93)
But i need output like below. Expected output:
data = (1,2,3)
Upvotes: 0
Views: 936
Reputation: 1465
We don't know how is encoded
the original string of bytes.
Suppose they are in json:
import json
tuple(json.loads(data))
#('1', '2', '3')
If they (unfortunately) are a py representation:
tuple(eval(data))
#('1', '2', '3')
The main question is, how are they encoded in a string?
Upvotes: 1
Reputation: 61920
One approach is first to decode the byte-string then use ast.literal_eval
to convert it to list:
from ast import literal_eval
data = b'["1","2","3"]'
res = literal_eval(data.decode("utf-8"))
res = tuple(res)
print(res)
Output
('1', '2', '3')
Upvotes: 1