How to check if the string is empty?

后端 未结 25 1861
佛祖请我去吃肉
佛祖请我去吃肉 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: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.

提交回复
热议问题