Search code examples
pythonstringlambdanonetype

convert string to array with int and None


I was trying this code:

data=str([1, 2, 3, None, None, 4, 5])
temp=data.strip('][').split(', ')
array=list(map(lambda x: None if x==None else int(x), temp))
print(array)

However I get this error:

ValueError: invalid literal for int() with base 10: 'None'

How can I get this to put the array back into an array? Thanks


Solution

  • Rather converting the list to a Python-specific string representation, use a standard (or at least commonly used) encoding like JSON.

    lst = [1,2,3, None, None, 4, 5]
    data = json.dumps(lst)
    assert lst == json.loads(data)