Python中判断字符串是否为数字的三个方法isdecimal 、isdigit、isnumeric的差别

isdecimal 、isdigit、isnumeric这三个字符串方法都用于判断字符串是否为数字,为什么用三个方法呢?他们的差别是什么内?
isdecimal:是否为十进制数字符,包括Unicode数字、双字节全角数字,不包括罗马数字、汉字数字、小数;
isdigit:是否为数字字符,包括Unicode数字,单字节数字,双字节全角数字,不包括汉字数字,罗马数字、小数
isnumeric:是否所有字符均为数值字符,包括Unicode数字、双字节全角数字、罗马数字、汉字数字,不包括小数。

我们定义一个函数来进行验证:

def isnumber(s):
	 print(s+' isdigit: ',s.isdigit())
	 print(s+' isdecimal: ',s.isdecimal())
	 print(s+' isnumeric: ',s.isnumeric())

执行函数isnumber(‘123’),三个都是True,执行函数isnumber(‘123.0’),三个都是False,执行函数isnumber(‘壹贰叁’),打印分别是False、False、True,罗马数字也是一样的结果。

>>> isnumber('123')
123 isdigit:  True
123 isdecimal:  True
123 isnumeric:  True
>>> isnumber('123.0')
123.0 isdigit:  False
123.0 isdecimal:  False
123.0 isnumeric:  False
>>> isnumber('壹贰叁')
壹贰叁 isdigit:  False
壹贰叁 isdecimal:  False
壹贰叁 isnumeric:  True

老猿Python,跟老猿学Python!

posted on 2019-06-29 22:03  老猿Python  阅读(1341)  评论(0编辑  收藏  举报