2

astring ('a','tuple')

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

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

The str vs. unicode distinction disappears in Python 3 - unicode and str are now just str.
0

use isinstance(), general syntax is:

if isinstance(var, type):
    # do something

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.