1

I have an example data in the form of a stringed array in python, Input: '[1,2,3,4,5]'

And I want to remove the quotes and convert the data into an array element, Output: [1,2,3,4,5]

When I try int(), I get the following error: ValueError: invalid literal for int() with base 10: '[1,2,3,4,5]'

Any help on how to solve this?

Manav Mishra
  • 103
  • 1
  • 6

2 Answers2

0

There is a neat function in python called eval() that you can use. This function basically evaluates a single python expression and runs it. So if you have eval('print('Hello World!!')') the eval functions will try to run the string as a python code. For more info on eval() read this article by w3schools.

For your problem, you can use a code like this:

myArrString = '[1,2,3,4]'
myArrList = eval(myArrString)
ARK1375
  • 790
  • 3
  • 19
  • 1
    @ManavMishra not really related to this specific question but if you are looking into using _eval()_ or _literal_eval()_ in the future, go check out this [link](https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval) Long story short: eval - can be dangerous if you read untrusted source. literal_eval -is considering only some syntax valid – pst Jun 22 '21 at 09:24
0

You can use the ast module

import ast
stringed = '[1,2,3,4,5]'
result = ast.literal_eval(stringed)
pst
  • 92
  • 7