Home > Mobile >  How I Convert a string representation of a nested list into a nested list?
How I Convert a string representation of a nested list into a nested list?

Time:03-31

I have a string representing a nested list: string = [[1,2,3],[4,5,6]]

And a would like to convert it to a list: list = [[1, 2, 3], [4, 5, 6]]

I've tried using string.split("]'[").split(', ') but it still returning [ ['1,2,3],[4,5,6'] ]

Any help? Thanks!

CodePudding user response:

Assuming that you have a string like string = "[[1,2,3],[4,5,6]]" and you want to convert it to a list object like lst = [[1,2,3],[4,5,6]], you could simply use the eval method:
lst = eval(string)

CodePudding user response:

If I understood your question correctly, you need eval() builtin. Starting from python 3.9, better use ast.literal_eval(node_or_string), it more safer:

from ast import literal_eval

a_str = '[[1,2,3],[4,5,6]]'
b_list = eval(a_str)
print(b_list)
# from python 3.9 better to use this, instead of eval():
c_list = literal_eval(a_str)
print(c_list)

Read:

https://docs.python.org/3/library/ast.html#ast.literal_eval https://docs.python.org/3/library/functions.html#eval

CodePudding user response:

If you don't have problem using external library, You can use pyyaml to achieve that:

>>> from yaml import CLoader as Loader, CDumper as Dumper
>>> import yaml
>>> string = "[[1,2,3],[4,5,6]]"
>>> yaml.load(string, Loader=Loader)
[[1, 2, 3], [4, 5, 6]]

CodePudding user response:

ast.literal_eval(string) is what you're looking for. In this case that would end up looking like

from ast import literal_eval

string = "[[1,2,3],[4,5,6]]"
list = literal_eval(string)
print(list)

Using eval from python is considered dangerous, especially if the input for it is done outside of code. This is a safe alternative that still does what you're looking for.

There's a couple of issues with your first approach (ignore this part if you don't care to be lectured). First, it seems like your variable string is actually already a list instead of a string. I'll be assuming this is a typo and you meant string = "[[1,2,3],[4,5,6]]" instead.

str.split(sep) takes a string that will be used as the separator, so str.split("]'[") will try to split on the exact string "]'[" where it seems you're expecting it to split on any single one of those characters. The result is that you are given a list of a single string, ["[[1,2,3],[4,5,6]]"].

  • Related