Home > Software engineering >  Split a string with bracketed elements
Split a string with bracketed elements

Time:12-31

I am solving a problem from codewars and I'm stuck on a step

I have a strings like this defr[fr]i##abde[fgh]ijk and i want add separatar between element ,but that should be the case for elements inside brackets , so the output should be [d,e,f,r,[fr],i,#,#,a,b,d,e,[fgh],i,j,k]

I have tried looping with different conditions,

and I came up with this code

        if land[i] == "[":
            print(land[i])
            j = i  1
            while land[j] != "]":
                print(land[j])
                j  =1
            else:
                number_of_shelter.append(land[i:j 1])
        else:
            continue

but it appends only bracketed elements

can someone tell me the approach that how can i append other elements along with bracketed ones

OTHER EXAMPLES: ##[a]b[c]#>>> [#,#,[a],b,[c],#]

[a]#[b]#[c] >>> [[a],#,[b],#,[c]]

CodePudding user response:

This works :

def foo(s):
    output = ""
    inBracket = False
    for i in s:
        if i == "[" or (inBracket == True and i != "]"):
            output = i
            inBracket = True
        else:
            inBracket = False
            output  = i   ","
    if output[len(output)] == ",":
        output = output[:-1]
    return output

CodePudding user response:

Here is the working code

str = "defr[fr]i##abde[fgh]ijk"
arr = []
in_the_bracket = False
for i in str:
    if i == '[':
        in_the_bracket = True
        chr = ''
    if in_the_bracket:
        chr = chr   i
    else:
        arr.append(i)

    if i == ']':
        in_the_bracket = False
        arr.append(chr)
print(arr)
  • Related