为什么 isdigit() return false 在 float 上?
Why isdigit() return false on float?
我想检查我的值是带点的浮点数还是逗号,但是 isdigit() return false 带点。我想知道为什么以及如何经历它。
> value = "0.0"
> print value.isdigit():
>>> False
我的代码是:
if "." in value and value.isdigit()
print "ok"
str.isdigit()
只有在字符串中的所有字符都是 位数 时才会 return 为真。 .
是标点符号,不是数字。
来自Python 3 str.isdigit()
documentation:
Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal
(对于 Python 2,对于 str
对象,仅考虑 ASCII 数字(0
到 9
),但对于 unicode
对象同样的定义适用。
查看符合该描述的 official Numeric Property definitions specification; there are 708 Unicode codepoints。
将此简化为通用 unicode 类别,Unicode 中的数字类型有一个以 N
开头的类别,但 .
没有:
>>> import unicodedata
>>> unicodedata.category(u'.')
'Po'
P
代表这里的punctuation,o
代表other.
反之亦然,仅包含数字的字符串并不总是可以转换为浮点数或数字:
>>> unicodedata.name(u'\u2080')
'SUBSCRIPT ZERO'
>>> unicodedata.category(u'\u2080')
'No'
>>> unicodedata.digit(u'\u2080')
0
>>> u'\u2080'.isdigit()
True
>>> float(u'\u2080')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'decimal' codec can't encode character u'\u2080' in position 0: invalid decimal Unicode string
所以就 float()
而言,下标零并不是真正的 0,但它 是 一个数字。
如果要测试字符串是否为有效浮点数,请使用 float
并捕获 ValueError
:
def is_float(string):
try:
float(string)
return True
except ValueError:
return False
我想检查我的值是带点的浮点数还是逗号,但是 isdigit() return false 带点。我想知道为什么以及如何经历它。
> value = "0.0"
> print value.isdigit():
>>> False
我的代码是:
if "." in value and value.isdigit()
print "ok"
str.isdigit()
只有在字符串中的所有字符都是 位数 时才会 return 为真。 .
是标点符号,不是数字。
来自Python 3 str.isdigit()
documentation:
Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal
(对于 Python 2,对于 str
对象,仅考虑 ASCII 数字(0
到 9
),但对于 unicode
对象同样的定义适用。
查看符合该描述的 official Numeric Property definitions specification; there are 708 Unicode codepoints。
将此简化为通用 unicode 类别,Unicode 中的数字类型有一个以 N
开头的类别,但 .
没有:
>>> import unicodedata
>>> unicodedata.category(u'.')
'Po'
P
代表这里的punctuation,o
代表other.
反之亦然,仅包含数字的字符串并不总是可以转换为浮点数或数字:
>>> unicodedata.name(u'\u2080')
'SUBSCRIPT ZERO'
>>> unicodedata.category(u'\u2080')
'No'
>>> unicodedata.digit(u'\u2080')
0
>>> u'\u2080'.isdigit()
True
>>> float(u'\u2080')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'decimal' codec can't encode character u'\u2080' in position 0: invalid decimal Unicode string
所以就 float()
而言,下标零并不是真正的 0,但它 是 一个数字。
如果要测试字符串是否为有效浮点数,请使用 float
并捕获 ValueError
:
def is_float(string):
try:
float(string)
return True
except ValueError:
return False