Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly convert a list[str] into a list[int]?

I have this route in flask that receive a data from the client side(Angular). I am getting the data with the use of data = request.data.decode("UTF-8") the result will be this one: "[1,2,3,4,5]". In order for me to remove these "[]", I used data1 = data.strip("[]"), the result will be this one "1,2,3,4,5". In order for me to make it a list[str] I used this one data2 = [data1], the output will be now ["1,2,3,4,5"]. Lastly, in order for me to convert it in a list[int], I used this one finalData = list(map(int,data2[0].split(","))), which will result in this one [1,2,3,4,5].

The Problem:
But everytime I used this code flask always prompt this error :

File "C:\Users\bagal\Desktop\hello_flask\dummyLogin.py", line 69, in reportData

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

finalData = list(map(int,data2[0].split(",")))

ValueError: invalid literal for int() with base 10: ”

The Code:

 @app.route("/adminData", methods = ['POST', 'GET'])
    def reportData():
         data = request.data.decode("UTF-8")
         data1 = data.strip("[]")
         data2 = [data1]
        finalData = list(map(int,data2[0].split(",")))

Note: I am using the fetched data in machine learning model, and sorry for a long explanation at the top, hope someone will help.

>Solution :

The entire string looks to be a valid python expression containing only literals. You could use ast.literal_eval() to process the entire string at once.

>>> import ast
>>> ast.literal_eval("[1,2,3,4,5]")
[1, 2, 3, 4, 5]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading