Home > OS >  Can I convert a string into a list[int] in flask/python?
Can I convert a string into a list[int] in flask/python?

Time:02-27

This is what the string looks like:

 dataString = "[100, 200, 300, 400, 500]"

This is what I want to convert into:

 dataConverted = [100, 200, 300, 400, 500]

CodePudding user response:

Your string is follows JSON format, so you can use json.loads

import json
dataString = "[100, 200, 300, 400, 500]"
dataConverted = json.loads(dataString)
print(dataConverted) # [100, 200, 300, 400, 500]

CodePudding user response:

dataString = "[100, 200, 300, 400, 500]"
from ast import literal_eval

data = literal_eval(dataString)
print(data)
print(type(data))

//[100, 200, 300, 400, 500]
//<class 'list'>

CodePudding user response:

list_str = "[100, 200, 300, 400, 500]"

# split by using ',' 
items = list_str.split(",")

new_list = []

# add items to new list
for item in items:
  new_list.append(int(item.replace("[", "").replace("]", "")))

print(new_list)
  • Related