Search code examples
pythonnonetype

Pythonic way to convert the string "None" to a proper None


I could create an if statement, bet there might be a better way.


Solution

  • You could use ast.literal_eval:

    In [6]: import ast
    
    In [7]: ast.literal_eval('None') is None
    Out[7]: True
    

    However, an if-statement or ternary expression would be faster if all you need is to convert 'None' to None:

    x = None if x == 'None' else x