how to tell a variable is iterable but not a string

后端 未结 8 2152
小蘑菇
小蘑菇 2020-12-02 09:23

I have a function that take an argument which can be either a single item or a double item:

def iterable(arg)
    if #arg is an iterable:
        print \"yes         


        
8条回答
  •  温柔的废话
    2020-12-02 10:02

    I realise this is an old post but thought it was worth adding my approach for Internet posterity. The function below seems to work for me under most circumstances with both Python 2 and 3:

    def is_collection(obj):
        """ Returns true for any iterable which is not a string or byte sequence.
        """
        try:
            if isinstance(obj, unicode):
                return False
        except NameError:
            pass
        if isinstance(obj, bytes):
            return False
        try:
            iter(obj)
        except TypeError:
            return False
        try:
            hasattr(None, obj)
        except TypeError:
            return True
        return False
    

    This checks for a non-string iterable by (mis)using the built-in hasattr which will raise a TypeError when its second argument is not a string or unicode string.

提交回复
热议问题