gpt4 book ai didi

python - python3.x中的StringType和NoneType

转载 作者:IT老高 更新时间:2023-10-28 20:34:02 26 4
gpt4 key购买 nike

我有一个在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com