2

astring ('a','tuple')

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

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

3 Answers3

8
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).

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • 3
    +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 Dec 13 '09 at 11:52
5
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
  • 92,113
  • 3
  • 26
  • 27
0

use isinstance(), general syntax is:

if isinstance(var, type):
    # do something
Markus Amalthea Magnuson
  • 8,415
  • 4
  • 41
  • 49
Ahmad Dwaik
  • 963
  • 1
  • 9
  • 13