Home > OS >  Convert string to array of strings using python
Convert string to array of strings using python

Time:02-03

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

CodePudding user response:

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(' ')]
print(result)

['apple', 'bat', 'cat']
  • Related