How to check if the string is empty?

后端 未结 25 1540
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  • Another easy way could be to define a simple function:

    def isStringEmpty(inputString):
        if len(inputString) == 0:
            return True
        else:
            return False
    
    0 讨论(0)
  • 2020-11-22 15:16
    a = ''
    b = '   '
    a.isspace() -> False
    b.isspace() -> True
    
    0 讨论(0)
  • 2020-11-22 15:16

    How about this? Perhaps it's not "the most elegant", but it seems pretty complete and clear:

    if (s is None) or (str(s).strip()==""): // STRING s IS "EMPTY"...
    
    0 讨论(0)
  • 2020-11-22 15:16

    Responding to @1290. Sorry, no way to format blocks in comments. The None value is not an empty string in Python, and neither is (spaces). The answer from Andrew Clark is the correct one: if not myString. The answer from @rouble is application-specific and does not answer the OP's question. You will get in trouble if you adopt a peculiar definition of what is a "blank" string. In particular, the standard behavior is that str(None) produces 'None', a non-blank string.

    However if you must treat None and (spaces) as "blank" strings, here is a better way:

    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())
    

    Examples:

    >>> 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
    

    Meets the @rouble requirements while not breaking the expected bool behavior of strings.

    0 讨论(0)
  • 2020-11-22 15:16

    As prmatta posted above, but with mistake.

    def isNoneOrEmptyOrBlankString (myString):
        if myString:
            if not myString.strip():
                return True
            else:
                return False
        return False
    
    0 讨论(0)
  • 2020-11-22 15:18

    You may have a look at this Assigning empty value or string in Python

    This is about comparing strings that are empty. So instead of testing for emptiness with not, you may test is your string is equal to empty string with "" the empty string...

    0 讨论(0)
提交回复
热议问题