基本上我想这样做:

obj = 'str'
type ( obj ) == string

我试着:

type ( obj ) == type ( string )

但这并没有起作用。

还有,其他类型的呢?例如,我无法复制NoneType。


当前回答

对于其他类型,请查看types模块:

>>> import types
>>> x = "mystring"
>>> isinstance(x, types.StringType)
True
>>> x = 5
>>> isinstance(x, types.IntType)
True
>>> x = None
>>> isinstance(x, types.NoneType)
True

注:类型检查是个坏主意。

其他回答

首先,避免所有类型比较。它们很少是必要的。有时,它们有助于检查函数中的参数类型——即使这种情况也很少见。错误类型的数据将引发异常,而这正是您所需要的。

所有基本转换函数都将映射为类型函数。

type(9) is int
type(2.5) is float
type('x') is str
type(u'x') is unicode
type(2+3j) is complex

还有其他一些情况。

isinstance( 'x', basestring )
isinstance( u'u', basestring )
isinstance( 9, int )
isinstance( 2.5, float )
isinstance( (2+3j), complex )

顺便说一句,None从来不需要任何这种类型的检查。None是唯一的实例。None对象是一个单例对象。只检查None

variable is None

顺便说一下,一般情况下不要使用上述方法。使用普通异常和Python本身的自然多态。

你很接近了!字符串是模块,不是类型。你可能想比较obj的类型和字符串的类型对象,即str:

type(obj) == str  # this works because str is already a type

另外:

type(obj) == type('')

注意,在python2中,如果obj是unicode类型,那么上述两种方法都不能工作。isinstance()也不会。看看约翰对这篇文章的评论,了解如何解决这个问题……我已经试着记住它大约10分钟了,但是有一个记忆块!

isinstance()

在你的例子中,isinstance("this is a string", str)将返回True。

你可能还想读这个:http://www.canonical.org/~kragen/isinstance/

我想这个就可以了

if isinstance(obj, str)

我用type(x) == type(y)

例如,如果我想检查一个数组:

type( x ) == type( [] )

字符串检查:

type( x ) == type( '' ) or type( x ) == type( u'' )

如果您想检查None,请使用is

x is None