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


Groups > comp.lang.python > #69759

Re: A data conversion question

From Peter Otten <__peter__@web.de>
Subject Re: A data conversion question
Date 2014-04-06 10:37 +0200
Organization None
References <lhr23k$6dh$1@news.albasani.net>
Newsgroups comp.lang.python
Message-ID <mailman.8946.1396773491.18130.python-list@python.org> (permalink)

Show all headers | View raw


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.

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

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

csiph-web