赞
赏
Python 判断 字符串 是否是数字主要有三种方法,分别为 isnumeric() 、isdigit() 和 isdecimal()。
函数 | 描述 |
---|---|
isdecimal() | 是否为十进制数字符,包括 Unicode 数字、双字节全角数字,不包括罗马数字、汉字数字、小数。 |
isdigit() | 是否为数字字符,包括 Unicode 数字,单字节数字,双字节全角数字,不包括汉字数字,罗马数字、小数。 |
isnumeric() | 是否所有字符均为数值字符,包括 Unicode 数字、双字节全角数字、罗马数字、汉字数字,不包括小数。 |
使用纯数字,比较isdecimal() isdigit() isnumeric()区别
print("嗨客网(www.haicoder.net)")
# 使用纯数字,比较isdecimal() isdigit() isnumeric()区别
def isnumber(s):
print(s+' isdigit: ', s.isdigit())
print(s+' isdecimal: ', s.isdecimal())
print(s+' isnumeric: ', s.isnumeric())
print(isnumber('123'))
程序运行后,控制台输出如下:
首先,我们定义一个函数 isnumber() 传入一个字符串参数,最终打印该字符串 变量 的 isdigit()、isdecimal() 和 isnumeric() 的运行结果。
我们传入一个纯数字的字符串,最终三个函数都返回 True,即纯数字的字符串使用这三个函数返回的结果是一致的。
使用带小数的数字字符串,比较isdecimal() isdigit() isnumeric()区别
print("嗨客网(www.haicoder.net)")
# 使用带小数的数字字符串,比较isdecimal() isdigit() isnumeric()区别
def isnumber(s):
print(s+' isdigit: ', s.isdigit())
print(s+' isdecimal: ', s.isdecimal())
print(s+' isnumeric: ', s.isnumeric())
print(isnumber('123.1'))
程序运行后,控制台输出如下:
首先,我们定义一个函数 isnumber() 传入一个字符串参数,最终打印该字符串变量的 isdigit()、isdecimal() 和 isnumeric() 的运行结果。
我们传入一个带小数的数字字符串,最终三个函数都返回 False,即带小数的数字字符串使用这三个函数返回的结果是一致的。
使用大写中文数字字符串,比较isdecimal() isdigit() isnumeric()区别
print("嗨客网(www.haicoder.net)")
# 使用大写中文数字字符串,比较isdecimal() isdigit() isnumeric()区别
def isnumber(s):
print(s+' isdigit: ', s.isdigit())
print(s+' isdecimal: ', s.isdecimal())
print(s+' isnumeric: ', s.isnumeric())
print(isnumber('壹贰叁'))
程序运行后,控制台输出如下:
首先,我们定义一个函数 isnumber() 传入一个字符串参数,最终打印该字符串变量的 isdigit()、isdecimal() 和 isnumeric() 的运行结果。
我们传入一个大写中文数字字符串,最终只有 isnumeric() 返回了 True。
Python 判断字符串是否是数字主要有三种方法,分别为 isnumeric() 、isdigit() 和 isdecimal()。
isdecimal() :是否为十进制数字符,包括 Unicode 数字、双字节全角数字,不包括罗马数字、汉字数字、小数。
isdigit() :是否为数字字符,包括Unicode数字,单字节数字,双字节全角数字,不包括汉字数字,罗马数字、小数。
isnumeric() :是否所有字符均为数值字符,包括Unicode数字、双字节全角数字、罗马数字、汉字数字,不包括小数。