Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #69753 > unrolled thread

A data conversion question

Started byMok-Kong Shen <mok-kong.shen@t-online.de>
First post2014-04-06 10:09 +0200
Last post2014-04-06 10:37 +0200
Articles 2 — 2 participants

Back to article view | Back to comp.lang.python


Contents

  A data conversion question Mok-Kong Shen <mok-kong.shen@t-online.de> - 2014-04-06 10:09 +0200
    Re: A data conversion question Peter Otten <__peter__@web.de> - 2014-04-06 10:37 +0200

#69753 — A data conversion question

FromMok-Kong Shen <mok-kong.shen@t-online.de>
Date2014-04-06 10:09 +0200
SubjectA data conversion question
Message-ID<lhr23k$6dh$1@news.albasani.net>
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

[toc] | [next] | [standalone]


#69759

FromPeter Otten <__peter__@web.de>
Date2014-04-06 10:37 +0200
Message-ID<mailman.8946.1396773491.18130.python-list@python.org>
In reply to#69753
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.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web