0

How to convert string into new_list without using eval(), exec() or any other libraries?

string = '[1,2,3,[4,5,6],7,[8,[9,10]],11]'

new_list = [1,2,3,[4,5,6],7,[8,[9,10]],11]
  • I think you forgot a comma after the 8 – Hylke Nov 09 '20 at 11:36
  • use `literal_eval`. difference between `eval` please see this page https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval – Fu Hanxi Nov 09 '20 at 11:58
  • 3
    Why should anyone care to answer if you do not even show us what you have done to come to a solution yourself? – Thijmen Nov 09 '20 at 12:06
  • Does this answer your question? [How to convert string representation of list to a list?](https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list) specifically [this answer](https://stackoverflow.com/a/55931430/6045800) – Tomerikoo Nov 09 '20 at 12:19
  • 1
    Also, why wouldn't you want to use built-ins or libraries? Is this a school exercise? If so, you should show your effort and ask about ***that***, and not expect to get free code – Tomerikoo Nov 09 '20 at 12:22

1 Answers1

1

The biggest problem you're facing with this question is that you cannot say how deep the list will nest, therefore the best option is to make a recursive function that evaluates the string and calls itself whenever it encounters a new list.

Another issue you will run in to is that a number can be multiple digits long and it would not be a clean solution to only assume it might be max 2 digits. A while loop to find all consecutive digits is probably the best solution for that. Here is my implementation:

def get_number(str, idx):
    """Find all consecutive digits and return them and the updated index"""
    number = ""
    while str[idx].isdigit():
        number += str[idx]
        idx += 1
    return int(number), idx


def recursive_list(str, idx):
    """Transform a string to list, recursively calling this function whenever a nested list is encountered."""
    lst = []
    # Loop over the entire string
    while idx < len(str):
        char = str[idx]
        # When encountering a digit, get the entire number
        if char.isdigit():
            number, idx = get_number(str, idx)
            lst.append(number)
            idx += 1
        # When encountering a closing bracket, return the (sub-)list
        elif char == ']':
            return lst, idx + 1
        # When encountering an opening bracket, append the nested list
        elif char == '[':
            nested, idx = recursive_list(str, idx + 1)
            lst.append(nested)
        else:
            # Go to the next character if we encounter anything else
            idx += 1
    return lst, idx


def main():
    """Transform a string to a list."""
    str = "[1,2,3,[4,5,6],7,[8,[9,10]],11]"
    new_list, _ = recursive_list(str, 1)
    print(new_list)


if __name__ == "__main__":
    main()
Hylke
  • 171
  • 1
  • 15