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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top