简体   繁体   中英

check if varible is either of type string or int

I am trying to check whether variable data is either of type string or integer so that i can work on it.If its none of the above it is supposed to return false. I have tried to use isinstance but it requires data to be of both types which is impossible. Any better method of doing it? Here is my code:

     if isinstance(data(int, str)):
         return True
     else:
         return false

You could use boolean or :

>>> isinstance(3,int) or isinstance(3,str)
True
>>> isinstance("3",int) or isinstance("3",str)
True
>>> isinstance([3],int) or isinstance([3],str)
False

or specify a tuple of possible types :

>>> isinstance(3, (int, str))
True
>>> isinstance("3", (int, str))
True
>>> isinstance([3], (int, str))
False

So in your case, it wouldn't be :

isinstance(data(int, str))

but

isinstance(data, (int, str))

As a matter of fact,you can use a tuple of classes as 2nd argument to isinstance .

isinstance(var,(list,int))

isinstance(object, classinfo)

If classinfo is a tuple of class or type objects (or recursively, other such tuples), return true if object is an instance of any of the classes or types. If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised.

You can use the isinstance(object, classinfo) built-in function.

This should do the job

def isStrOrInt(myVar):
  return isinstance(myVar,int) or isinstance(myVar,str)


print(isStrOrInt(5))   # True
print(isStrOrInt('5')) # True
print(isStrOrInt([]))  # False
print(isStrOrInt('Dinosaurs are Awesome!')) # True
print(isStrOrInt(3.141592653589793238462 )) # False (Because it's a decimal not an int)

Here's the running version: https://repl.it/Fw63/1


This is what the documentation says:

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns false. If classinfo is a tuple of type objects (or recursively, other such tuples), return true if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.

Basically, isinstance takes 2 parameters, the first is the variable you want to check, and the second is the data type/ class you want to check if it is an instance of (in your case int or str ). This tutorial explains it well.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM