Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into array in Python

I have a string with the following structure.

string = "[abcd, abc, a, b, abc]"

I would like to convert that into an array. I keep using the split function in Python but I get spaces and the brackets on the start and the end of my new array. I tried working around it with some if statements but I keep missing letters in the end from some words.

Keep in mind that I don't know the length of the elements in the string. It could be 1, 2, 3 etc.

like image 603
George Kostopoulos Avatar asked Jun 06 '17 08:06

George Kostopoulos


1 Answers

Assuming your elements never end or start with spaces or square brackets, you could just strip them out (the bracket can be stripped out before splitting):

arr = [ x.strip() for x in string.strip('[]').split(',') ]

It gives as expected

print (arr)
['abcd', 'abc', 'a', 'b', 'abc']

The nice part with strip is that it leaves all inner characters untouched. With:

string = "[ab cd, a[b]c, a, b, abc]"

You get: ['ab cd', 'a[b]c', 'a', 'b', 'abc']

like image 101
Serge Ballesta Avatar answered Sep 24 '22 01:09

Serge Ballesta