How to detect list versus string
__peter__ at web.de
Fri Jun 11 19:15:20 CEST 2004
Jonathon McKitrick wrote:
> This sounds simpler that it is, hopefully ;-)
> I have a method that builds a dynamic combo box. Before I do that, I set
> a class variable to the new list of items.
> def make_new_cat_box(self, cats):
if isinstance(cats, basestring):
cats = [cats]
> self.cat_list = cats
> Sounds simple. But sometimes, my combo box will only have one choice
> available. When I call this method with a list of one string, the string
> is split up, and my combo box now has a separate item for each letter in
> string. What I obviously want to do is detect when the object coming in
> a list or a string. type() isn't as useful as I had hoped, and len() will
>>> value = "123"
>>> if type(value) == type(""):
... print "It's a string"
It's a string
> give me the length of the string, so I cannot tell if it is a string or a
> list of more that one item.
> There has to be a simple solution.
I'd prefer isinstance() over type(cats) == type(""). If you are sure there
won't be any unicode strings you can use isinstance(cats, str) instead of
the basestring variant shown above.
More information about the Python-list