Here's an example code:
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
Now, If I ran this and typed in the Python Shell:
test()
I would get
'test = True'
But, If I type:
test("This is a string")
I do not get returned "test2 = True" which Is what I want, I simply get returned nothing.
I know why this happens but how would I go about doing it correctly and make it so when I type in the Python Shell:
test("String")
or any other string, I would get returned "test2 = True" ?
A string object is not identical to the str
type object. It is an instance of that type, not the type itself.
You could use the type()
function to test for the types of objects:
>>> type('this is a string') is str
True
but you generally want to use the isinstance()
function instead:
>>> isinstance('this is a string', str)
True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.