How to check if the string is empty?

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

    The only really solid way of doing this is the following:

    if "".__eq__(myString):
    

    All other solutions have possible problems and edge cases where the check can fail.

    len(myString)==0 can fail if myString is an object of a class that inherits from str and overrides the __len__() method.

    Similarly myString == "" and myString.__eq__("") can fail if myString overrides __eq__() and __ne__().

    For some reason "" == myString also gets fooled if myString overrides __eq__().

    myString is "" and "" is myString are equivalent. They will both fail if myString is not actually a string but a subclass of string (both will return False). Also, since they are identity checks, the only reason why they work is because Python uses String Pooling (also called String Internment) which uses the same instance of a string if it is interned (see here: Why does comparing strings using either '==' or 'is' sometimes produce a different result?). And "" is interned from the start in CPython

    The big problem with the identity check is that String Internment is (as far as I could find) that it is not standardised which strings are interned. That means, theoretically "" is not necessary interned and that is implementation dependant.

    The only way of doing this that really cannot be fooled is the one mentioned in the beginning: "".__eq__(myString). Since this explicitly calls the __eq__() method of the empty string it cannot be fooled by overriding any methods in myString and solidly works with subclasses of str.

    Also relying on the falsyness of a string might not work if the object overrides it's __bool__() method.

    This is not only theoretical work but might actually be relevant in real usage since I have seen frameworks and libraries subclassing str before and using myString is "" might return a wrong output there.

    Also, comparing strings using is in general is a pretty evil trap since it will work correctly sometimes, but not at other times, since string pooling follows pretty strange rules.

    That said, in most cases all of the mentioned solutions will work correctly. This is post is mostly academic work.

提交回复
热议问题