Search code examples
pythonstringlistabstract-syntax-tree

How to get list of strings from list-like string that includes nan?


Here is toy-example, I've string like this:

import numpy as np
z = str([np.nan, "ab", "abc"])

Printed it looks like "[nan, 'ab', 'abc']" but I've to process z = str([np.nan, "ab", "abc"])

I want to get from z list of strings excluding nan:

zz = ["ab", "abc"]

To be clear: z is input (string, that look list-like), zz is wanted output (list)

There is no problem if z doesn't contain nan, in such ast.literal_eval(z) do the job, but with nan I get error about malformed node or string.

Note: np.nan doesn't have to be first.


Solution

  • What about:

    eval(z,{'nan':'nan'}) # if you can tolerate then: 
    [i for i in eval(z,{'nan':'nan'}) if i != 'nan']
    

    It may have security considerations.