Skip to main content
 首页 » 编程设计

python之检查变量是字符串类型还是整数类型

2025年05月04日1552php

我正在尝试检查变量数据是字符串类型还是整数类型,以便我可以对其进行处理。如果以上都不是,则应该返回 false。我曾尝试使用 isinstance 但它要求数据是两种类型,这是不可能的。有什么更好的方法吗? 这是我的代码:

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

请您参考如下方法:

事实上,您可以使用类的元组作为 isinstance 的第二个参数。

isinstance(var,(list,int)) 

是实例(对象,类信息)

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.