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

Paul Lernmark picture Paul Lernmark · Oct 21, 2014 · Viewed 11.1k times · Source

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

Answer

unutbu picture unutbu · Oct 21, 2014

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