0

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)

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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')

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.