-1

I have a string that is

string_list = '[15,30]'

How can I convert it to make it into a list with the values as integers?

Expected Output:

integer_list = [15,30]
  • 1
    It depends on what serialization format that string is using. If its straight python, `ast.literal_eval` may work. If its JSON, `json.loads` is a good choice. – tdelaney Feb 25 '20 at 22:02
  • 1
    Does this answer your question? [Convert string representation of list to list](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) – Scriptim Feb 25 '20 at 22:03
  • 1
    @stovfl its not a list of strings he wants as a list of ints. Its a single string that he wants to make as a list of ints. – Chris Doyle Feb 25 '20 at 22:05
  • `i = [int(i) for i in '[15,30]'[1:-1].split(',')]` – stovfl Feb 25 '20 at 22:54

3 Answers3

2

Use json, it will load a python object from a string version of that object . loads is for load str, if I remember correctly.

import json

integer_list = json.loads(string_list)

More info on json: https://docs.python.org/3/library/json.html

Xhattam
  • 195
  • 1
  • 11
2

You can use ast.literal_eval

import ast

string_list = '[15,30]'
integer_list = ast.literal_eval(string_list)
print(integer_list)
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42
  • I'm curious, what's the diff between `ast` and `json` ? Is there one better than the other and why ? – Xhattam Feb 25 '20 at 22:05
  • 2
    @Xhattam `ast.literal_eval` can evaluate Python literals (it is a safer form of `eval`, which can evaluate arbitrary python expressions). `json` is a, well, JSON parser. – juanpa.arrivillaga Feb 25 '20 at 22:06
  • Fair enough, thanks for the explanation ! – Xhattam Feb 25 '20 at 22:07
  • For a list of integers, json and ast.literal_eval are much the same. There are edge cases like `[1,2,3,4,]` doesn't work in json. ast.literal_eval is python only. If you are sharing this data with other programs, json is the better choice. – tdelaney Feb 25 '20 at 22:09
-1

What about that ?

string_list = '[15,30]'
string_list = string_list[1:]
string_list = string_list[:-1]
integer_list = string_list.split(",")

for item in integer_list :
    item = int(item)
Gilles Walther
  • 126
  • 1
  • 7