首页 文章

最优雅的方法来检查Python中的字符串是否为空?

提问于
浏览
1017

Python是否有类似空字符串变量的地方?:

if myString == string.empty:

无论检查空字符串值的最优雅方法是什么?每次检查一个空字符串都没有那么好,我发现硬编码 "" .

22 回答

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

    如果你只是使用

    not var1
    

    不可能将一个boolean False 变量与空字符串 '' 区分开来:

    var1 = ''
    not var1
    > True
    
    var1 = False
    not var1
    > True
    

    但是,如果向脚本添加简单条件,则会产生以下差异:

    var1  = False
    not var1 and var1 != ''
    > True
    
    var1 = ''
    not var1 and var1 != ''
    > False
    
  • 27
    str = ""
    if not str:
       print "Empty String"
    if(len(str)==0):
       print "Empty String"
    
  • -8

    正如上面张贴的prmatta,但有错误 .

    def isNoneOrEmptyOrBlankString (myString):
        if myString:
            if not myString.strip():
                return True
            else:
                return False
        return False
    
  • 4

    如果你想区分空字符串和空字符串,我建议使用 if len(string) ,否则,我建议使用简单的 if string ,正如其他人所说的那样 . 关于充满空白字符串的警告仍然适用,所以不要忘记 strip .

  • -1

    以下是其中之一

    foo is ''
    

    甚至

    empty = ''
    foo is empty
    
  • 64

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

    if not my_string:
    

    但是,您可能希望剥离空格,因为:

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

    你可能应该更明确一点,除非你确定这个字符串已经通过了某种验证,并且是一个可以通过这种方式测试的字符串 .

  • -2

    当您逐行读取文件并想确定哪一行是空的时,请确保使用 .strip() ,因为"empty"行中有新行字符:

    lines = open("my_file.log", "r").readlines()
    
    for line in lines:
        if not line.strip():
            continue
    
        # your code for non-empty lines
    
  • 1
    if my_string is '':
    

    我没有注意到任何答案中的特定组合 . 我找了

    is ''
    

    在发布之前的答案中 .

    if my_string is '': print ('My string is EMPTY') # **footnote
    

    我认为这就是原始海报试图达到的目标......尽可能接近英语并遵循可靠的编程实践 .

    if my_string is '':
        print('My string is EMPTY')
    else:
        print(f'My string is {my_string}')
    

    角色的角色我觉得这个解决方案很好 .

    我注意到 None 已经进入讨论,所以我们进一步加入并进一步压缩:

    if my_string is '': print('My string is Empty')
    elif my_string is None : print('My string.... isn\'t')
    else: print(f'My string is {my_string}')
    
  • 5

    回应@ 1290 . 对不起,没办法在评论中格式化块 . None 值在Python中不是空字符串,也不是(空格) . 安德鲁·克拉克的答案是正确的: if not myString . @rouble的答案是特定于应用程序的,并没有回答OP的问题 . 如果您对"blank"字符串采用特殊定义,则会遇到麻烦 . 特别是,标准行为是 str(None) 产生 'None' ,一个非空字符串 .

    但是,如果您必须将 None 和(空格)视为"blank"字符串,这是一种更好的方法:

    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的要求,同时不破坏字符串的预期 bool 行为 .

  • 0

    当字符串为空时, if stringname: 给出 false . 我想它不能比这更简单 .

  • 0

    对于那些期望像apache StringUtils.isBlank或Guava Strings.isNullOrEmpty这样的行为的人:

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

    我曾经写过类似于Bartek的回答和javascript启发的内容:

    def isNotEmpty(s):
        return bool(s and s.strip())
    

    测试:

    print isNotEmpty("")    # False
    print isNotEmpty("   ") # False
    print isNotEmpty("ok")  # True
    print isNotEmpty(None)  # False
    
  • 7

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

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

    来自PEP 8,在“Programming Recommendations” section中:

    对于序列,(字符串,列表,元组),请使用空序列为假的事实 .

    所以你应该使用:

    if not some_string:
    

    要么:

    if some_string:
    

    只是为了澄清,如果序列是空的或不是,则序列在布尔上下文中是 evaluatedFalseTrue . 它们是 not equalFalseTrue .

  • 1
    not str(myString)
    

    对于空的字符串,此表达式为True . 非空字符串,None和非字符串对象都将产生False,但需要注意的是,对象可能会覆盖__str__以通过返回伪值来阻止此逻辑 .

  • 9

    测试空或空白字符串(更短的方式):

    if myString.strip():
        print("it's not an empty or blank string")
    else:
        print("it's an empty or blank string")
    
  • 2

    我发现硬编码(sic)“”每次检查空字符串都不太好 .

    清洁代码方法

    这样做: foo == "" 是非常糟糕的做法 . "" 是一个神奇的 Value . 你永远不应该检查魔法值(通常称为magical numbers

    您应该做的是与描述性变量名称进行比较 .

    描述性变量名称

    有人可能认为"empty_string"是一个描述性的变量名 . It isn't .

    在你去之前做 empty_string = "" 并认为你有一个很好的变量名来比较 . 这不是"descriptive variable name"的意思 .

    一个好的描述性变量名称基于其上下文 . 你必须考虑空字符串 is .

    • 它来自哪里 .

    • 为什么会这样 .

    • 为什么需要检查它 .

    简单表单字段示例

    您正在构建一个用户可以输入值的表单 . 您想检查用户是否写了某些内容 .

    一个好的变量名可能是 not_filled_in

    这使得代码非常易读

    if formfields.name == not_filled_in:
        raise ValueError("We need your name")
    

    彻底的CSV解析示例

    您正在解析CSV文件,并希望将空字符串解析为 None (由于CSV完全基于文本,因此在不使用预定义关键字的情况下无法表示 None

    一个好的变量名可能是 CSV_NONE

    如果你有一个新的CSV文件用 None 表示另一个字符串而不是 "" ,这使得代码很容易改变和适应

    if csvfield == CSV_NONE:
        csvfield = None
    

    关于这段代码是否正确,没有任何问题 . 很明显,它做了它应该做的事情 .

    比较这个

    if csvfield == EMPTY_STRING:
        csvfield = None
    

    这里的第一个问题是,为什么空弦需要特殊处理?

    这将告诉未来的编码人员应该始终将空字符串视为 None .

    这是因为它将业务逻辑(什么CSV值应该是 None )与代码实现混合在一起(我们实际比较的是什么)

    两者之间需要有一个separation of concern .

  • 1

    剥离之前我会测试一下 . 另外,我会使用空字符串为False(或Falsy)的事实 . 这种方法类似于Apache's StringUtils.isBlankGuava's Strings.isNullOrEmpty

    This is what I would use to test if a string is either None OR Empty OR Blank:

    def isBlank (myString):
        if myString and myString.strip():
            #myString is not None AND myString is not empty or blank
            return False
        #myString is None OR myString is empty or blank
        return True
    

    And, the exact opposite to test if a string is not None NOR Empty NOR Blank:

    def isNotBlank (myString):
        if myString and myString.strip():
            #myString is not None AND myString is not empty or blank
            return True
        #myString is None OR myString is empty or blank
        return False
    

    More concise forms of the above code:

    def isBlank (myString):
        return not (myString and myString.strip())
    
    def isNotBlank (myString):
        return bool(myString and myString.strip())
    
  • 12

    根据我的经验,测试 "" 并不总是有效 . 这个简单的测试一直对我有用:

    if MyString == 'None'
    

    要么

    if MyString != 'None'
    

    读取Excel电子表格我希望在使用以下while循环使列变空时停止:

    while str(MyString) != 'None':
    
  • 8

    空字符串是"falsy",这意味着它们在布尔上下文中被视为false,因此您可以这样做:

    if not myString:
    

    如果您知道您的变量是字符串,那么这是首选方法 . 如果您的变量也可以是其他类型,那么您应该使用 myString == "" . 有关布尔上下文中为false的其他值,请参阅Truth Value Testing上的文档 .

  • 318

    你可以看看这个Assigning empty value or string in Python

    这是关于比较空的字符串 . 所以不要用 not 测试空虚,你可以测试你的字符串是否等于空字符串 "" 空字符串...

相关问题