转换字符串“无"的 Pythonic 方法到适当的 None [英] Pythonic way to convert the string "None" to a proper None

查看:60
本文介绍了转换字符串“无"的 Pythonic 方法到适当的 None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以创建一个 if 语句,打赌可能有更好的方法.

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

推荐答案

您可以使用 ast.literal_eval:

You could use ast.literal_eval:

In [6]: import ast

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

但是,if-statement三元表达式如果您只需要将 'None' 转换为 None,则速度会更快:

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

这篇关于转换字符串“无"的 Pythonic 方法到适当的 None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆