A data conversion question

M

Mok-Kong Shen

A newbie's question of curiosity:

If I have

g=[1,[2]] and

bg=bytearray(str(g),"latin-1")

could I somehow get back from bg a list g1 that is the same as g?

Thanks in advance.

M. K. Shen
 
P

Peter Otten

Mok-Kong Shen said:
A newbie's question of curiosity:

If I have

g=[1,[2]] and

bg=bytearray(str(g),"latin-1")

could I somehow get back from bg a list g1 that is the same as g?

Not for arbitrary values, but for lists, ints, and a few other types that's
not a problem:
g = [1, [2]]
bg = bytearray(str(g), "latin-1")
bg bytearray(b'[1, [2]]')
import ast
ast.literal_eval(bg.decode("latin-1"))
[1, [2]]

See also https://docs.python.org/dev/library/ast.html#ast.literal_eval

Note that while eval() instead of ast.literal_eval() would also work you
should avoid it. eval() can execute arbitrary Python code and is thus a big
security whole when applied to user-provided data.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top