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:
We use the toString() method of the list to convert the list into a string.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With