Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list to a string and back

I have a virtual machine which reads instructions from tuples nested within a list like so:

[(0,4738),(0,36),  (0,6376),(0,0)] 

When storing this kind of machine code program, a text file is easiest, and has to be written as a string. Which is obviously quite hard to convert back.

Is there any module which can read a string into a list/store the list in a readable way?

requirements:

  • Must be human readable in stored form (hence "pickle" is not suitable)
  • Must be relatively easy to implement
like image 978
Xandros Avatar asked Jul 22 '13 20:07

Xandros


People also ask

Can we convert list to string in Java?

We use the toString() method of the list to convert the list into a string.

How do you join a list into a string in Python?

The most pythonic way of converting a list to string is by using the join() method. The join() method is used to facilitate this exact purpose. It takes in iterables, joins them, and returns them as a string. However, the values in the iterable should be of string data type.


1 Answers

Use the json module:

string = json.dumps(lst) lst = json.loads(string) 

Demo:

>>> import json >>> lst = [(0,4738),(0,36), ...  (0,6376),(0,0)] >>> string = json.dumps(lst) >>> string '[[0, 4738], [0, 36], [0, 6376], [0, 0]]' >>> lst = json.loads(string) >>> lst [[0, 4738], [0, 36], [0, 6376], [0, 0]] 

An alternative could be to use repr() and ast.literal_eval(); for just lists, tuples and integers that also allows you to round-trip:

>>> from ast import literal_eval >>> string = repr(lst) >>> string '[[0, 4738], [0, 36], [0, 6376], [0, 0]]' >>> lst = literal_eval(string) >>> lst [[0, 4738], [0, 36], [0, 6376], [0, 0]] 

JSON has the added advantage that it is a standard format, with support from tools outside of Python support serialising, parsing and validation. The json library is also a lot faster than the ast.literal_eval() function.

like image 69
Martijn Pieters Avatar answered Oct 19 '22 16:10

Martijn Pieters