A data conversion question
Peter Otten
__peter__ at web.de
Sun Apr 6 04:37:58 EDT 2014
Mok-Kong Shen wrote:
> 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.
More information about the Python-list
mailing list