How to check if the string is empty?

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

    If you want to differentiate between empty and null strings, I would suggest using if len(string), otherwise, I'd suggest using simply if string as others have said. The caveat about strings full of whitespace still applies though, so don't forget to strip.

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

    I find this elegant as it makes sure it is a string and checks its length:

    def empty(mystring):
        assert isinstance(mystring, str)
        if len(mystring) == 0:
            return True
        else:
            return False
    
    0 讨论(0)
  • 2020-11-22 15:10

    From PEP 8, in the “Programming Recommendations” section:

    For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

    So you should use:

    if not some_string:
    

    or:

    if some_string:
    

    Just to clarify, sequences are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True.

    0 讨论(0)
  • 2020-11-22 15:10
    not str(myString)
    

    This expression is True for strings that are empty. Non-empty strings, None and non-string objects will all produce False, with the caveat that objects may override __str__ to thwart this logic by returning a falsy value.

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

    I did some experimentation with strings like '', ' ', '\n', etc. I want isNotWhitespace to be True if and only if the variable foo is a string with at least one non-whitespace character. I'm using Python 3.6. Here's what I ended up with:

    isWhitespace = str is type(foo) and not foo.strip()
    isNotWhitespace = str is type(foo) and not not foo.strip()
    

    Wrap this in a method definition if desired.

    0 讨论(0)
  • 2020-11-22 15:12
    str = ""
    if not str:
       print "Empty String"
    if(len(str)==0):
       print "Empty String"
    
    0 讨论(0)
提交回复
热议问题