Search code examples
pythonstring-parsing

How can I convert a list of strings into numerical values?


I want to find out how to convert a list of strings into a list of numbers.

I have a php form through which user enters values for x and y like this:

X: [1,3,4]
Y: [2,4,5]

These values are stored into database as varchars. From there, these are called by a python program which is supposed to use them as numerical (numpy) arrays. However, these are called as plain strings, which means that calculation can not be performed over them. Is there a way to convert them into numerical arrays before processing or is there something else which is wrong?


Solution

  • You can use list comprehension along with the strip() and split() function to turn this into numeric values.

    x = '[1,3,4]'
    new_x = [int(i) for i in x.strip('[]').split(',')]
    new_x
    [1, 3, 4]
    

    Use this list of ints as you see fit, e.g., passing them on to numpy etc.

    from numpy import array
    
    a = array(new_x)
    a
    array([1, 3, 4])
    
    a * 4
    array([ 4, 12, 16])