How can I tell if a python variable is a string or a list?

后端 未结 8 1808
孤独总比滥情好
孤独总比滥情好 2020-12-02 19:45

I have a routine that takes a list of strings as a parameter, but I\'d like to support passing in a single string and converting it to a list of one string. For example:

8条回答
  •  悲&欢浪女
    2020-12-02 20:23

    If you have more control over the caller, then one of the other answers is better. I don't have that luxury in my case so I settled on the following solution (with caveats):

    def islistlike(v):
       """Return True if v is a non-string sequence and is iterable. Note that
       not all objects with getitem() have the iterable attribute"""
       if hasattr(v, '__iter__') and not isinstance(v, basestring):
           return True
       else:
           #This will happen for most atomic types like numbers and strings
           return False
    

    This approach will work for cases where you are dealing with a know set of list-like types that meet the above criteria. Some sequence types will be missed though.

提交回复
热议问题