How to convert string to list() #17313
Replies: 6 comments 4 replies
-
You can use json >>> l = [1,2,3,4,5,]
>>> import json
>>> lt = json.dumps(l)
>>> lt
'[1, 2, 3, 4, 5]'
>>> lv = json.loads(lt)
>>> lv
[1, 2, 3, 4, 5] |
Beta Was this translation helpful? Give feedback.
-
I gave it a try but after the dump() and load() I'm still stuck with a string. Perhaps I will read up on json import features. |
Beta Was this translation helpful? Give feedback.
-
Or >>> s = "[5, 3, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5]"
>>> q = [int(n) for n in s if not n in ", []"]
>>> print(q)
>>> [5, 3, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5] This answers the original question, but is not a serious solution. It will break with anything other than single digits. JSON is the way to go. |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
You need to read more about serialization. The most used serialization format is
import struct
import json
import os
DATA = [5, 3, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5]
# 15 bytes (unsigned char) (0 - 255)
# little endian (doesn't matter with single bytes)
MY_STRUCT = "<15B"
def filesize(file):
def human(size):
for unit in ("Bytes", "KiB", "MiB"):
if size < 1024:
break
size /= 1024
return f"{size:.0f} {unit}"
return f"{file:<16s}: {human(os.stat(file)[6])}"
def write_struct(data: list[int], file_out: str):
"""
Writes 15 bytes to a file as a struct.
"""
if len(data) != 15:
raise ValueError("Data must be consist of 15 integers as iterable (list or tuple)")
with open(file_out, "wb") as fd_out:
fd_out.write(struct.pack(MY_STRUCT, *data))
def write_json(data: list[int], file_out: str):
"""
Write the content of the list to a json file.
"""
with open(file_out, "w") as fd_out:
json.dump(data, fd_out)
def read_struct(file_in: str) -> list[int]:
"""
Read struct from file and return the result.
"""
with open(file_in, "rb") as fd_in:
# struct.unpack returns the data in a tuple, not a list
# converting to a list to fit the type hint
return list(struct.unpack(MY_STRUCT, fd_in.read()))
def read_json(file_in: str) -> list[int]:
"""
Read json from file and return the result.
"""
with open(file_in) as fd_in:
return json.load(fd_in)
write_struct(DATA, "data_struct.bin")
write_json(DATA, "data_json.json")
data_from_struct = read_struct("data_struct.bin")
data_from_json = read_json("data_json.json")
print("data_from_struct:", data_from_struct)
print("data_from_json: ", data_from_json)
print(filesize("data_struct.bin"))
print(filesize("data_json.json")) If you want to be more flexible, JSON is a good solution. Use of |
Beta Was this translation helpful? Give feedback.
-
See this doc.
In a microcontroller context it is also inefficient as it implies runtime execution of the compiler. |
Beta Was this translation helpful? Give feedback.
-
Firstly I'm a newbie just so you know. I've used the open() builtin function to write a list() to a config.txt file. To do so I had to
convert it to a string (buffer protocol needed) with: cfg_str = str(cfg_list). Upon reading the config.txt file the list comes back as a string.
print of original cfg_list()
Write [5, 3, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5] <class 'list'>
print of returned file read:
Read [5, 3, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5] <class 'str'>
same print output but I need it to be a list again.
I was going to attempt manipulation the string but I'm hoping there is a simple
hack to simply cast the string back to a list .
So any suggestions from the more experienced programmers out there?
Thanks Denis Lebel
Beta Was this translation helpful? Give feedback.
All reactions