0

I have a string that looks similar to the following:

string = "hello,2,test,1,[4,something,3],1,2"

When I split the string by commas I get the following array:

['hello', '2', 'test', '1', '[4', 'something', '3]', '1', '2']

How could I efficiently split the original string to instead get the following:

['hello', '2', 'test', '1', '[4,something,3]', '1', '2']
2
  • Can '[...]' strings be nested, like '[a, b, [c, d], e]'? Commented Jul 7, 2019 at 0:21
  • Are you eventually trying to turn this into ['hello', 2, 'test', 1, [4, 'something', 3], 1, 2]? Commented Jul 7, 2019 at 0:44

3 Answers 3

2

Use regex

import re re.split(r",\s*(?![^[]*])",string)

Result:

['hello', '2', 'test', '1', '[4,something,3]', '1', '2']

Note this answer assumes no nested []

Sign up to request clarification or add additional context in comments.

1 Comment

This fails for hello,2,test,1,[4,something,3],1,2,[4,[something],3]
0

Here is one way:

string = "hello,2,test,1,[4,something,3],1,2"
string2 = string.split(",")
res = []
temp = []
found = False

for item in string2:
    if (not(found)):
        if "[" in item:
            found = True
            temp = []
            temp.append(item[1:])
        else:
            res.append(item)

    else:
        if "]" in item:
            found = False
            temp.append(item[:-1])
            final = str(temp).replace("'", "")
            res.append(final)
        else:
            temp.append(item)

print(res)

Output:

['hello', '2', 'test', '1', '[4, something, 3]', '1', '2']

Comments

0

You can do it with a regular expression:

import re

string = "hello,2,test,1,[4,something,3],1,2"
x = re.findall(r'\[[^\]]+\](?=,|\b)|[^,]+(?=,|\b)', string)

x contains ['hello', '2', 'test', '1', '[4,something,3]', '1', '2'].

In the regex we have two cases separated by | (or). The first should handle the longer cases [something, in, brackets] the second can handle the simple cases. In case you are not familiar with it (?=,|\b) is a positive lookahead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.