What is the Pythonic Way of Differentiating Between a String and a List?

No need to import modules, isinstance(), str and unicode (versions before 3 — there’s no unicode in 3!) will do the job for you.

Python 2.x:

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(u'', (str, unicode))
True
>>> isinstance('', (str, unicode))
True
>>> isinstance([], (str, unicode))
False

>>> for value in ('snowman', u'☃ ', ['snowman', u'☃ ']):
...     print type(value)
... 
<type 'str'>
<type 'unicode'>
<type 'list'>

Python 3.x:

Python 3.2 (r32:88445, May 29 2011, 08:00:24) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance('☃ ', str)
True
>>> isinstance([], str)
False

>>> for value in ('snowman', '☃ ', ['snowman', '☃ ']):
...     print(type(value))
... 
<class 'str'>
<class 'str'>
<class 'list'>

From PEP008:

Object type comparisons should always use isinstance() instead of comparing types directly.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)