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

if myString == string.empty:

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


当前回答

我会在剥离之前测试无。此外,我将使用空字符串为False(或Falsy)的事实。这种方法类似于Apache的StringUtils.isBlank或Guava的Strings.isNullOrEmpty

这是我用来测试字符串是否为None或Empty或Blank的方法:

def isBlank (myString):
    return not (myString and myString.strip())

如果字符串不是None NOR Empty NOR Blank,则与测试正好相反:

def isNotBlank (myString):
    return bool(myString and myString.strip())

其他回答

回复@1290。抱歉,无法格式化注释中的块。None值在Python中不是空字符串,也不是(空格)。安德鲁·克拉克的答案是正确的:如果不是myString。@rouble的答案是特定于应用程序的,不会回答OP的问题。如果你对什么是“空白”字符串采用一个特殊的定义,你会遇到麻烦。特别是,标准行为是str(None)生成“None”,一个非空字符串。

但是,如果您必须将None和(空格)视为“空白”字符串,这里有一个更好的方法:

class weirdstr(str):
    def __new__(cls, content):
        return str.__new__(cls, content if content is not None else '')
    def __nonzero__(self):
        return bool(self.strip())

示例:

>>> normal = weirdstr('word')
>>> print normal, bool(normal)
word True

>>> spaces = weirdstr('   ')
>>> print spaces, bool(spaces)
    False

>>> blank = weirdstr('')
>>> print blank, bool(blank)
 False

>>> none = weirdstr(None)
>>> print none, bool(none)
 False

>>> if not spaces:
...     print 'This is a so-called blank string'
... 
This is a so-called blank string

满足@rouble要求,同时不破坏字符串的预期布尔行为。

如果您不完全确定您的输入是否真的是字符串,我建议您另外使用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>

我曾经写过类似于Bartek的答案和javascript的灵感:

def is_not_blank(s):
    return bool(s and not s.isspace())

测试:

print is_not_blank("")    # False
print is_not_blank("   ") # False
print is_not_blank("ok")  # True
print is_not_blank(None)  # False

如果您想区分空字符串和空字符串,我建议使用If-len(string),否则,我建议像其他人所说的那样简单地使用If-string。但是,关于充满空格的字符串的警告仍然适用,所以不要忘记剥离。

a = ''
b = '   '
a.isspace() -> False
b.isspace() -> True