如何判断一个字符串是数字

anonymity
anonymity 原创
2019-05-25 11:35:51 11833浏览

Python中字符串处理的方法函数:

str.isnumeric(): True if 只包含数字;otherwise False。注意:此函数只能用于unicode string

str.isdigit(): True if 只包含数字;otherwise False。

str.isalpha():True if 只包含字母;otherwise False。

str.isalnum():True if 只包含字母或者数字;otherwise False。

示例字符串:

str_1 = "123"

str_2 = "Abc"

str_3 = "123Abc"

代码处理过程:

#用isdigit函数判断是否数字
print(str_1.isdigit())
Ture
print(str_2.isdigit())
False
print(str_3.isdigit())
False
#用isalpha判断是否字母
print(str_1.isalpha())    
False
print(str_2.isalpha())
Ture    
print(str_3.isalpha())    
False
#isalnum判断是否数字和字母的组合
print(str_1.isalnum())    
Ture
print(str_2.isalnum())
Ture
print(str_1.isalnum())    
Ture

注意:如果字符串中含有除了字母或者数字之外的字符,比如空格,也会返回False

严格解析:有除了数字或者字母外的符号(空格,分号,etc.)都会False
isalnum()必须是数字和字母的混合
isalpha()不区分大小写

以上就是如何判断一个字符串是数字的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。