-4

I am using python 3, I have this below list

["Device","kdi","fdf,"False"]

How can i turn this string to list. So i can read values of 0 as device. value OF 1 as kdi, and so on. Currently when am trying to read, the value of 0 am getting is [ than value of 1 is " than value of 2 is d....

user3278732
  • 1,576
  • 9
  • 26
  • 60
  • Would you mind including a bit more detail around the task at hand? Some code? – C.Nivs Mar 03 '20 at 23:59
  • 1
    sounds like an XY-problem... How do you get this string from the first place? – Tomerikoo Mar 04 '20 at 00:12
  • @Tomerikoo It's hardly an XY problem - it's a normal and sensible enough problem that the standard library function `json.loads` does it. (That's also why it's an obvious duplicate.) – kaya3 Mar 04 '20 at 00:13
  • @kaya3 maybe I misuse the term XY, what I meant is if OP provide more context to the problem it might be solved in a different more easy way from the start – Tomerikoo Mar 04 '20 at 00:14
  • The string probably comes from a file or a network request. – kaya3 Mar 04 '20 at 00:15
  • @kaya3 not always a safe assumption, I'm afraid. Often, people are dumping the string representation of some list object to a text file and calling that serialization. In which case, `json.loads` won't work. – juanpa.arrivillaga Mar 04 '20 at 00:19
  • @juanpa.arrivillaga In that case, the other standard library function `ast.literal_eval` also works. The fact that there are two options built in rather underscores the fact that it's a usual and reasonable thing to do. – kaya3 Mar 04 '20 at 00:22

1 Answers1

0

Use ast.literal_eval:

>>> from ast import literal_eval
>>> s = '["Device","kdi","fdf","False"]'
>>> l = literal_eval(s)
>>> print(l[0])
Device
mrzo
  • 1,509
  • 1
  • 8
  • 18