Convert string with a list syntax to a list object
Several options are possible. Here is Option 1, which uses `ast.literal_eval` function. Note, as the input string might contain any possible sequence of characters, that will not be a valid Python list, it is important to bear in mind the errors that this function can raise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import ast def get_list_from_string(input_lst_string: str) -> list: """ Applies `ast.literal_eval` helper to `convert` input string to a list, and checks if the resulting object is a list indeed. If the string contains other Python's literal, like integer, ast.literal_eval will return it, as it is designed to parse any literals. As ast.literal_eval can be considered relatively safe from attacks, when with a string some executable code is passed, as function `understands` literals only (i.e., not a functions, classes, calls, operators). But, according to docs, it is not free from, say, potential memory exhaustion or stack exhaustion: https://docs.python.org/3/library/ast.html#ast.literal_eval :param input_lst_string: string containing Python's list representation :return: outpu_list - list parsed from string """ try: output_list: list = ast.literal_eval(input_lst_string) except (ValueError, SyntaxError, TypeError, MemoryError, RecursionError) as exc: # if you know typical problems that might occur with your input values, you can process # the error caught further, for example, to provide meaningful error message raise Exception("<Meaningful error message goes here>") from exc if not isinstance(output_list, list): raise Exception("The resulting object is not a list") return output_list # usage input_list_string: str = "print('test')" # error, not a literal input_list_string: str = "[[1, 2, ]" # error, malformed list input_list_string: str = "[1, [2, 3, [1, 2, 5, 6.7]]]" # ok list_as_python_object: list = get_list_from_string(input_list_string) print(list_as_python_object) |
Related pages
...
Navigate from here