没有vs Python中的空字符串

Geo*_*rge 7 python null nonetype

我有一个连接到数据库的现有应用程序.它在Python 2.7下运行.

应用程序在使用None和""填充没有值的变量的方式上不一致.我想使这一点保持一致,并尝试以某种方式更新代码.

作为一个数据库人思考,我认为None与Null一样,并且会认为这是空变量的正确选择但是当应用程序执行类似的操作时这会导致问题

if variable.upper() == "X":
    #Do something
Run Code Online (Sandbox Code Playgroud)

如果变量为None类型,则会引发错误.

我可以

if variable is not None and variable.upper() == "X":
    #Do something
Run Code Online (Sandbox Code Playgroud)

但这似乎不必要地冗长.

是否应该如何处理这个问题的最佳做法?

obm*_*arg 11

你可以通过编写来略微减少代码

if variable and variable.upper() == "X":
    #Do something
Run Code Online (Sandbox Code Playgroud)

如果变量为none或为空,则它等效于False.