-3

I have this string

'["el1", "el2", "el3"]'

and it is a string, not an array, and all of 3 elements can change casually, but the elements are always 3. I want to create a variable for all the 3 elements, like

var1 = "el1"
var2 = "el2"
var3 = "el3"

A possible solution is converting this string into an array.. but i don't know how i can do it. Another solution is splicing the string but as always i don't know how i can do it. anyone can help?

The Thonnu
  • 3,578
  • 2
  • 8
  • 30
JacopoBiondi
  • 57
  • 1
  • 7
  • just to mention that regex is also a possible solution. the pattern is (?<=\")\w*(?=\"), and we can use re.findall(...) – lroth Aug 14 '22 at 16:36

3 Answers3

-1

It seems like your string is in the JSON format. You can make a list from it like this:

import json

string = '["el1", "el2", "el3"]'
list_from_string = json.loads(string)

print(list_from_string) # outputs ['el1', 'el2', 'el3']

It could also be done using the eval function as stated in the other answer. I advise against that, because eval can be very dangerous if you are getting the string as an input from the user.

You probably really don't want to create a variable for every item of your array input. If you create a list from it, you can then iter over it. You could for example use a for loop like this to print every item from your input array:

for i in list_from_string:
    print(i)

Output:

el1
el2
el3
Pavel40
  • 79
  • 3
-1

Using ast.literal_eval is the correct approach for this over using eval as it's unsafe:

from ast import literal_eval

s = '["el1", "el2", "el3"]'
 
var1, var2, var3 = literal_eval(s)

>>> var1
el1
>>> var2
el2
>>> var3
el3
Jab
  • 26,853
  • 21
  • 75
  • 114
-1

Try this out:

import ast

str = '["el1", "el2", "el3"]'
list_of_values = ast.literal_eval(str)

val1 = list_of_values[0]
val2 = list_of_values[1]
val3 = list_of_values[2]
print(val1)
print(val2)
print(val3)

output:

el1
el2
el3