detecting variable types

Scott David Daniels Scott.Daniels at Acm.Org
Wed Sep 22 17:51:58 EDT 2004


Byron wrote:
> Hi Jay,
> 
> You can detect the type of a variable by using the "types" module that 
> comes with Python.  Here is how to use it:
> 
> 
>     >>> import types
>     >>> name = "Steven"
>     >>> if type(name) is types.StringType:
>             print "Yes, name is a string."
> 
> 
> Hope this helps,
> 
> Byron
> ---
> 
> 
> Jay wrote:
> 
>> I'm sure this is a really dumb question, but how do you detect a variable
>> type in Python?
>>
>> For example, I want to know if the variable "a" is a list of strings or a
>> single string. How do I do this?
>>
>>

If you must switch on the type, use something like:

     ...
     if isinstance(vbl, (string, unicode)):
         vbl = [vbl]
     for element in vbl:
         ...

There are many more kinds of iterables than kinds of strings,
and you'll get fewer surprises with the above.

-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list