Python是否有类似空字符串变量的功能,您可以在其中执行以下操作:

if myString == string.empty:

无论如何,检查空字符串值最优雅的方法是什么?我发现每次检查空字符串的硬编码“”都不太好。


当前回答

以下是适用于任意数量空间的优雅解决方案。

def str_empty(s: str) -> bool:
    """Strip white space and count remaining characters."""
    return len(s.strip()) < 1


>>> str_empty(' ')
True

其他回答

最优雅的方法可能是简单地检查它是真是假,例如:

if not my_string:

但是,您可能需要删除空白,因为:

 >>> bool("")
 False
 >>> bool("   ")
 True
 >>> bool("   ".strip())
 False

但是,您可能应该对此更加明确一点,除非您确定该字符串已通过某种验证,并且是可以通过这种方式测试的字符串。

对于那些期望类似apacheStringUtils.isBlank或Guava Strings.isNullOrEmpty的行为的人:

if mystring and mystring.strip():
    print "not blank string"
else:
    print "blank string"

如果您不完全确定您的输入是否真的是字符串,我建议您另外使用isinstance(object,classinfo)链接,如示例所示。

如果不是,列表或True布尔值也可以计算为True。

<script type=“text/javascript”src=“//cdn.datacamp.com/dcl react.js.gz”></script><div data datacamp练习数据lang=“python”><code data type=“样本代码”>定义测试字符串(my_string):如果isinstance(my_string,str)和my_string:print(“这是我,字符串!->”+my_String)其他:print(“不,不,字符串”)def not_fully_test_string(my_string):如果my_string:print(“这是我,String???->”+str(my_String))其他:print(“不,不,字符串”)print(“测试字符串:”)test_string(“”)test_string(真)测试字符串([“string1”,“string2”])test_string(“我的字符串”)test_string(“”)print(“\n是否测试字符串?”)not_fully_test_string(“”)not_fully_test_string(真)not_fully_test_string([“string1”,“string2”])not_fully_test_string(“我的字符串”)not_fully_test_string(“”)</code></div>

if-stringname:当字符串为空时,返回false。我想再简单不过了。

这个怎么样?也许它不是“最优雅的”,但它似乎非常完整和清晰:

if (s is None) or (str(s).strip()==""): // STRING s IS "EMPTY"...