Convert string to array of strings using python


I have a string like "['apple' 'bat' 'cat']".
The string need to convert into array like:['apple','bat','cat']

>Solution :

remove the first [ and last ] elements of your string

then split the remaining string into their elements

Iterate then each element and remove the opening and closing quote (first and last element)

Merge everything in a list comprehension

my_string = "['apple' 'bat' 'cat']"
result = [i[1:-1] for i in my_string[1:-1].split(' ')]

['apple', 'bat', 'cat']

Leave a Reply Cancel reply