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']]

2

2 Answers 2

1

You can achieve this conversion using Python's ast module, which provides functions to safely evaluate Python expressions from strings containing Python literal structures.

Here is the code:

import ast

def convert_string_to_array(s):
    s = s.replace('M', "'Male'").replace('F', "'Female'")
    array = ast.literal_eval(s)
    return array

s = '[[M,,[10,20]],[F,,[7,9]]]'
result = convert_string_to_array(s)
print(result)
3
  • We'll also need to handle the double commas... Commented Apr 10, 2024 at 11:04
  • 1
    Could you explain why you do str.replace() for M and F?
    – Friedrich
    Commented Apr 10, 2024 at 11:24
  • Yes good question! Why not 'Fig' and 'Mango' ? Commented Apr 10, 2024 at 11:29
0

I've tried ast module

import ast

def convert_string_to_array(s):

    i=0

    while i<=len(s)-1:
        # Dealing the double comma issue
        if s[i]==',' and s[i+1]==',':
            s=s[:i+1]+"''"+s[i+1:]

        # Replace the string within the array with 'string'
        if s[i].isalpha() is True and s[i-1].isalpha() is False and s[i-1]!="'":
            i_head=i
        if s[i].isalpha() is True and s[i+1].isalpha() is False and s[i+1]!="'":
            i_tail=i
            s=s.replace(s[i_head:i_tail+1],f"'{s[i_head:i_tail+1]}'")

        i+=1
        print(i)


    array = ast.literal_eval(s)
    return array

s = '[[M,,[10,20]],[F,,[7,9]]]'
result = convert_string_to_array(s)
print(result)

The result would be [['M', '', [10, 20]], ['F', '', [7, 9]]]

This piece of code is modified based on Mr. Aryan Chauhan and Mr.Friedrich's code.

For the double comma issue, I added a empty string between the two commas.

Given the possibility of other strings appearing within the array, I've used isalpha() method to detect the string and convert it into f"'{string}'".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.