To check if o
is an instance of str
or any subclass of str
, use isinstance (this would be the "canonical" way):
(要检查是否o
是的实例str
或的任何子类str
,使用isinstance (这将是“规范”的方式):)
if isinstance(o, str):
To check if the type of o
is exactly str
(exclude subclasses):
(要检查o
的类型是否完全是str
(不包括子类):)
if type(o) is str:
The following also works, and can be useful in some cases:
(以下内容也可以使用,并且在某些情况下可能有用:)
if issubclass(type(o), str):
See Built-in Functions in the Python Library Reference for relevant information.
(有关相关信息,请参见Python库参考中的内置函数 。)
One more note: in this case, if you're using python 2, you may actually want to use:
(还有一点需要注意:在这种情况下,如果您使用的是python 2,则实际上可能要使用:)
if isinstance(o, basestring):
because this will also catch Unicode strings ( unicode
is not a subclass of str
; both str
and unicode
are subclasses of basestring
).
(因为这也会捕获Unicode字符串( unicode
不是str
的子类; str
和unicode
都是basestring
子类)。)
Note that basestring
no longer exists in python 3, where there's a strict separation of strings ( str
) and binary data ( bytes
). (请注意,在python 3中不再存在basestring
,在Python 3中,字符串( str
)和二进制数据( bytes
) 严格分开 。)
Alternatively, isinstance
accepts a tuple of classes.
(另外, isinstance
接受一个类的元组。)
This will return True if x is an instance of any subclass of any of (str, unicode): (如果x是(str,unicode)的任何子类的实例,则将返回True:)
if isinstance(o, (str, unicode)):
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…