TIMEX
TIMEX

Reputation: 271634

How to determine the datatype in Python?

astring ('a','tuple')

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

Upvotes: 2

Views: 909

Answers (3)

Ahmad Dwaik
Ahmad Dwaik

Reputation: 971

use isinstance(), general syntax is:

if isinstance(var, type):
    # do something

Upvotes: 0

Mike Hordecki
Mike Hordecki

Reputation: 97091

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

Upvotes: 5

jfs
jfs

Reputation: 414149

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

Upvotes: 8

Related Questions