无需导入模块,isinstance()、str 和 unicode(3 之前的版本——3 中没有 unicode!)将为您完成这项工作。
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'>
来自PEP008:
对象类型比较应始终使用isinstance(),而不是直接比较类型。