how to tell a variable is iterable but not a string

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

    Use isinstance (I don't see why it's bad practice)

    import types
    if not isinstance(arg, types.StringTypes):
    

    Note the use of StringTypes. It ensures that we don't forget about some obscure type of string.

    On the upside, this also works for derived string classes.

    class MyString(str):
        pass
    
    isinstance(MyString("  "), types.StringTypes) # true
    

    Also, you might want to have a look at this previous question.

    Cheers.


    NB: behavior changed in Python 3 as StringTypes and basestring are no longer defined. Depending on your needs, you can replace them in isinstance by str, or a subset tuple of (str, bytes, unicode), e.g. for Cython users. As @Theron Luhn mentionned, you can also use six.

    0 讨论(0)
  • 2020-12-02 10:26

    As you point out correctly, a single string is a character sequence.

    So the thing you really want to do is to find out what kind of sequence arg is by using isinstance or type(a)==str.

    If you want to realize a function that takes a variable amount of parameters, you should do it like this:

    def function(*args):
        # args is a tuple
        for arg in args:
            do_something(arg)
    

    function("ff") and function("ff", "ff") will work.

    I can't see a scenario where an isiterable() function like yours is needed. It isn't isinstance() that is bad style but situations where you need to use isinstance().

    0 讨论(0)
提交回复
热议问题