I have a string like "['apple' 'bat' 'cat']"
.
The string need to convert into array like:['apple','bat','cat']
Asked
Active
Viewed 79 times
-3
-
`['apple' 'bat' 'cat']` isn't a valid object in python, so you can't have that as starting point. You need to be precise in your questions. What's the starting object? The string `"['apple' 'bat' 'cat']"` or the array `['apple', 'bat', 'cat']`? – dirkgroten Feb 02 '23 at 14:30
-
So, this is a string "['apple' 'bat' 'cat']" and I want to convert this to array ['apple', 'bat', 'cat'] – Anonymous Feb 02 '23 at 14:32
-
Sorry for the unclear question. I edited the question again – Anonymous Feb 02 '23 at 14:37
-
1Decode the json – 0stone0 Feb 02 '23 at 14:38
-
So generally you want to convert a string of a literal to the equivalent value of the literal? – MisterMiyagi Feb 02 '23 at 14:39
-
Can elements contain spaces and/or quotes? – MisterMiyagi Feb 02 '23 at 14:49
1 Answers
1
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']

Sembei Norimaki
- 745
- 1
- 4
- 11