Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the datatype in Python?

Tags:

python

astring ('a','tuple')

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

like image 644
TIMEX Avatar asked Apr 12 '26 03:04

TIMEX


2 Answers

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

like image 62
jfs Avatar answered Apr 14 '26 19:04

jfs


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

like image 43
Mike Hordecki Avatar answered Apr 14 '26 19:04

Mike Hordecki