我有一个在 python2.x 代码库中使用 StringType 和 NoneType(类型模块)的代码库。在移植到 Python3 时,测试失败,因为 Python3.x 中的 types 模块没有上述两种类型。
我通过分别用“str”和“None”替换它们来解决问题。我想知道是否有另一种(正确的)方法可以做到这一点。我目前正在做的事情似乎确实有效,但我对此表示怀疑。
Should I stick to the approach I have followed or is there something wrong in what I have done? If so, how do I correct it?
最佳答案
检查None通常通过调用obj is None
来完成,而检查字符串通常是isinstance(obj, str)
。在 Python 2.x 中检测字符串和 unicode,您可以使用 isinstance(obj, basestring)
。
如果你使用 2to3
就足够了,但如果你需要一段代码同时在 Py2 和 Py3 中工作,你可能会得到类似的结果:
try:
return isinstance(obj, basestring)
except NameError:
return isinstance(obj, str)
关于python - python3.x中的StringType和NoneType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4232111/