今天写一个校验的时候,遇到了三个函数,记下来以备用吧
isinstance、isalnum、len
相比大家都知道type()函数,判断一个对象的数据类型:
In [1]: test = "abc123" In [2]: type(test) Out[2]: str In [3]: test = 123 In [4]: type(test) Out[4]: int
接下来介绍 isinstance数据类型,该函数用来判断是否为已知的数据类型,而type函数则是判断未知的数据类型,还是撸代码吧:
In [5]: test = "abc123" In [6]: isinstance(test,int) Out[6]: False In [7]: isinstance(test,(int,list)) Out[7]: False
基本语法就是 isinstance(对象,数据类型/(多个数据类型))
如果对象的数据类型包含在后面的数据类型中,则返回True,否则为False
In [8]: isinstance(test,(int,list,str)) Out[8]: True In [9]: isinstance(test,str) Out[9]: True
呃,那下一个 isalnum函数,判断字符串中是否由数字和字母组成,继续撸
In [10]: test = "abc123" In [11]: test.isalnum() Out[11]: True In [12]: test = "abc 123" In [13]: test.isalnum() Out[13]: False In [14]: test = "a" In [15]: test.isalnum() Out[15]: True In [16]: test = "" In [17]: test.isalnum() Out[17]: False
时间: 2024-10-09 22:09:41