How to detect list versus string

J

Jonathon McKitrick

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):
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 the
string. What I obviously want to do is detect when the object coming in is
a list or a string. type() isn't as useful as I had hoped, and len() will
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.

jm
 
P

Peter Otten

Jonathon said:
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
the
string. What I obviously want to do is detect when the object coming in
is
a list or a string. type() isn't as useful as I had hoped, and len() will
.... 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.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top