1

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]
1
  • remove first and last char of the string then split ', ' I think it's not efficient, so I ask it here. Commented Mar 12, 2013 at 3:04

3 Answers 3

5

Try this:

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

Read more about ast.literal_eval in python docs.

Sign up to request clarification or add additional context in comments.

Comments

2

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(',') ]

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.