How to check if the string is empty?

后端 未结 25 1842
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 14:47

Does Python have something like an empty string variable where you can do:

if myString == string.empty:

Regardless, what\'s the most elegan

25条回答
  •  执念已碎
    2020-11-22 15:19

    I would test noneness before stripping. Also, I would use the fact that empty strings are False (or Falsy). This approach is similar to Apache's StringUtils.isBlank or Guava'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())
    

提交回复
热议问题