是否有一种方法可以检查python中变量的类型是否为字符串,例如:

isinstance(x,int);

对于整数值?


当前回答

根据下面更好的答案进行编辑。向下走大约3个答案,找出basestring的cool值。

旧的回答: 注意unicode字符串,可以从多个地方获得,包括Windows中的所有COM调用。

if isinstance(target, str) or isinstance(target, unicode):

其他回答

根据下面更好的答案进行编辑。向下走大约3个答案,找出basestring的cool值。

旧的回答: 注意unicode字符串,可以从多个地方获得,包括Windows中的所有COM调用。

if isinstance(target, str) or isinstance(target, unicode):

我是这样做的:

if type(x) == type(str()):

So,

你有很多选项来检查你的变量是否是字符串:

a = "my string"
type(a) == str # first 
a.__class__ == str # second
isinstance(a, str) # third
str(a) == a # forth
type(a) == type('') # fifth

这个命令是有目的的。

我还想注意,如果你想检查一个变量的类型是否是特定的类型,你可以将变量的类型与一个已知对象的类型进行比较。

对于字符串,你可以使用这个

type(s) == type('')
>>> thing = 'foo'
>>> type(thing).__name__ == 'str' or type(thing).__name__ == 'unicode'
True