-2

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]
Markk
  • 25
  • 5

3 Answers3

1

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]
azro
  • 53,056
  • 7
  • 34
  • 70
0
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'>
Parvesh Kumar
  • 1,104
  • 7
  • 16
0
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)
Hamza
  • 1
  • 1
  • The 2 other solutions are way better, but let's improve yours. The bracket are here only once so don't apply the replace in the loop, but here with `str.strip` `items = list_str.strip("[]").split(",")` – azro Feb 27 '22 at 13:25
  • Thanks azro you are right, the strip is more efficent. – Hamza Feb 27 '22 at 13:52
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 27 '22 at 14:17