OnionCoder
OnionCoder

Reputation: 89

How to convert this nested string list into the actual list

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]

Upvotes: 0

Views: 63

Answers (1)

Hylke
Hylke

Reputation: 181

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()

Upvotes: 1

Related Questions