Python中的字符串类型检查
我正在尝试检查一个pandas数据框中的元素类型,这个元素看起来像是字符串:
type(atmdf.ix[row]['bid'])
<type 'str'>
但是,当我进行类型检查时,结果却是False:
type(atmdf.ix[row]['bid']) is 'str'
False
即使使用isinstance函数,我也得到了同样意外的结果:
isinstance(type(atmdf.ix[row]['bid']), str)
False
我哪里出错了?
附注:数据框中的内容大致是这样的:
atmdf.ix[row]['bid']
'28.5'
谢谢你!
1 个回答
2
你需要用 isinstance
来检查字符串本身,而不是检查它的类型:
In [2]: isinstance('string', str)
Out[2]: True
所以在你的例子中(不考虑 type(..)
):你应该用 isinstance(atmdf.ix[row]['bid'], str)
。
你第一次检查没有成功,因为你是把它和 str
(类型)进行比较,而不是和 'str'
(一个字符串)进行比较。