0

I have a string like:

f = "[['jack', 2002, 100000, 'dollar']]"

I want to change it to a list but my output:

['[', '[', "'", 'j', 'a', 'c', 'k', "'", ',', ' ', '1', '3', '5', '6', ',', ' ', '1', '0', '0', ',', ' ', "'", 'd', 'o', 'l', 'l', 'a', 'r', "'", ']', ']']

Can somebody help me:

my code:

f = "[['jack', 2002, 100000, 'dollar']]"
print(list(f))

what I expect:

[['jack', 2002, 100000, 'dollar']]
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
frg
  • 1
  • 1
  • Likely duplicate of: [Convert list of strings into multiple data types](https://stackoverflow.com/questions/16256639/convert-list-of-strings-into-multiple-data-types-in-one-line) – Sean Mar 29 '23 at 22:38
  • 1
    `ast.literal_eval(f)` – Barmar Mar 29 '23 at 22:38
  • 2
    @Sean It's not a list of strings. It's one string that contains the printed representation of a list. – Barmar Mar 29 '23 at 22:38
  • 1
    You cna use `eval`/`ast.literal_eval`, but you should *really consider why you have this string in the first place*. Where is this string coming from? Why do you find yourself in a position where you have a string that represents *python source code*? – juanpa.arrivillaga Mar 29 '23 at 22:38
  • @juanpa.arrivillaga: Given the contents, it's almost certainly the `repr` of a Python `list` (it uses single-quotes, so it's not legal JSON). I agree usually you want a better data serialization format. – ShadowRanger Mar 29 '23 at 22:40
  • @Sean: I found [the proper duplicate: "How to convert string representation of list to a list"](https://stackoverflow.com/q/1894269/364696), which is the "single string representing `list` to parsed `list` of things it represents" canonical. – ShadowRanger Mar 29 '23 at 22:40

0 Answers0