这是一个示例代码:
def test(something=None):
test = something is None
test2 = something is str
if(test == True):
return "test = True"
elif(test2 == True):
return "test2 = True"
else:
return
现在,如果我运行它并在Python Shell中输入:
test()
我会得到
'test = True'
但是,如果我键入:
test("This is a string")
我没有得到返回的“ test2 = True”,我只是什么都没有返回。
我知道为什么会发生这种情况,但是当我在Python Shell中键入内容时,我将如何正确地做到这一点呢?
test("String")
或任何其他字符串,我将返回“ test2 = True”?
字符串对象与str
类型对象不同。它是该类型的实例,而不是类型本身。
您可以使用该type()
功能测试对象的类型:
>>> type('this is a string') is str
True
但您通常想使用该isinstance()
函数:
>>> isinstance('this is a string', str)
True
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句