nyebelinn
nyebelinn

Reputation: 13

Convert string of list into list of int

how do I convert a string of integer list into a list of integers?

Example input: (type: string)

"[156, 100, 713]"

Example conversion: (type: list of int)

[156, 100, 713]

Upvotes: 1

Views: 134

Answers (3)

linbo
linbo

Reputation: 2431

>>> import json
>>> a = "[156, 100, 713]"
>>> json.loads(a)
[156, 100, 713]

Upvotes: 2

mgilson
mgilson

Reputation: 309841

use ast.literal_eval on it and you're done. Here you don't have all the security issues of regular eval and you don't need to worry about making sure your string is well formed, etc. Of course, if you really want to parse this thing yourself, you can do it with a pretty simple list-comprehension:

s = "[156, 100, 713]"
print [ int(x) for x in s.translate(None,'[]').split(',') ]

Upvotes: 2

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

Try this:

import ast
res = ast.literal_eval('[156, 100, 713]')

Read more about ast.literal_eval in python docs.

Upvotes: 5

Related Questions