Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 17419

Python converting string to array

$
0
0

I'm recently tring to make a python code to convert a string to array.For example:'[[M,,[10,20]],[F,,[7,9]]]' to [['M','',['10','20']],['F','',['7','9']]]

The reason I need it is that I am importing data from excel, which contains arrays in some of the cells, but I have absolutely no idea how to do that, and I would be very grateful if anyone could give me some hint.

I tried to ask chatGPT, but it gave me a code that did not work. Here is the code:

def parse_string(s):    result = []    current_list = []    i = 0    while i < len(s):        char = s[i]        if char == '[':            inner_result, remaining_string = parse_string(s[i + 1:])            current_list.append(inner_result)            i += len(inner_result) + 2          elif char == ']':            result.append(current_list)            return result, s[i + 1:]        elif char == ',':            if i > 0 and s[i - 1] == ',':                current_list.append('')            i += 1        elif char.isalnum() or char == '.':            j = i            while j < len(s) and (s[j].isalnum() or s[j] == '.' or s[j] == '-'):                j += 1            current_list.append(s[i:j])            i = j        else:            i += 1    return result, ''string = '[[M,,[10,20]],[F,,[7,9]]]'result, _ = parse_string(string)print(result)

And the result would be like: [[[[[['M', '', [['10', '20']], '20']], '', [['10', '20']], '20']], '', [['10', '20']], '20']]


Viewing all articles
Browse latest Browse all 17419

Latest Images

Trending Articles



Latest Images