Home > Software design >  How to convert a Python string in a list using no libraries
How to convert a Python string in a list using no libraries

Time:12-07

I'm trying to convert a string into a list wherever there is a bracket and using no libraries. So a string like '[wewr[sfs]]' should return ['w','e','w','r',['s','f','s']]. I'm not looking for a solution, just some guidance or advice over what is wrong with my code, the outcome I'm getting so far is ['w']

def my_function(s):
    final_list = []
    if d[0] == '[' and d[-1] == ']':
        for i in d:
            if i == '[':        
                final_list.append(my_function(d[(d.index('[') 1):(d.rindex(']'))]))
            
                i = d(d.rindex(']')  1)
                continue
            elif i == ']':
                break
            else:
                final_list.append(i)
                
            return final_list```

CodePudding user response:

You just have to think carefully about if-else-conditions:

def string_to_list(my_str):
    out = []
    for s in my_str.split('['):
        if ']' in s[:-1]:
            s1 = s.split(']')
            s1 = [list(s1[0])] list(s1[1])
        elif s[-1:] == ']':
            s1 = [list(s.strip(']'))]
        else:
            s1 = list(s)
        out.extend(s1)
    return out

print(string_to_list('[wewr[sfs]]'))
print(string_to_list('[wewr[sfs]da]'))
print(string_to_list('[wewr[sfs]da[ds]]'))
print(string_to_list('[wewr[sfs]da[ds][dfd]]'))

Output:

['w', 'e', 'w', 'r', ['s', 'f', 's']]
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a']
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a', ['d', 's']]
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a', ['d', 's'], ['d', 'f', 'd']]
  • Related