tags:

views:

151

answers:

3

astring ('a','tuple')

How do I determine if "x" is a tuple or string?

+5  A: 
isinstance(x, str)
isinstance(x, tuple)

In general:

isinstance(variable, type)

Checks whether variable is an instance of type (or its subtype) (docs).

PS. Don't forget that strings can also be in unicode (isinstance(x, unicode) in this case) (or isinstance(x, basestring) (thanks, J.F. Sebastian!) which checks for both str and unicode).

Mike Hordecki
The str vs. unicode distinction disappears in Python 3 - unicode and str are now just str.
Paul McGuire
+7  A: 
if isinstance(x, basestring):
   # a string
else:
   try: it = iter(x)
   except TypeError:
       # not an iterable
   else:
       # iterable (tuple, list, etc)

@Alex Martelli's answer describes in detail why you should prefer the above style when you're working with types in Python (thanks to @Mike Hordecki for the link).

J.F. Sebastian
+1, `isinstance(x, str)` and `type(x) is str` are both wrong as they don't handle unicode. Also, `isinstance()` is preferred over `type()` since it handles subclasses.
Ayman Hourieh
A: 

use isinstnce() general syntax is

if isinstnce(var,type):
    #do something
Ahmad Dwaik