how to tell a variable is iterable but not a string

后端 未结 8 2169
小蘑菇
小蘑菇 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:03

    2.x

    I would have suggested:

    hasattr(x, '__iter__')
    

    or in view of David Charles' comment tweaking this for Python3, what about:

    hasattr(x, '__iter__') and not isinstance(x, (str, bytes))
    

    3.x

    the builtin basestring abstract type was removed. Use str instead. The str and bytes types don’t have functionality enough in common to warrant a shared base class.

提交回复
热议问题