【问题标题】:Why isdigit() return false on float?为什么 isdigit() 在浮点数上返回 false?
【发布时间】:2017-04-26 12:18:52
【问题描述】:

我想检查我的值是带点还是逗号的浮点数,但 isdigit() 返回带点的 false。我想知道为什么以及如何通过它。

> value = "0.0"
> print value.isdigit():
>>> False

我的代码是:

if "." in value and value.isdigit()
    print "ok"

【问题讨论】:

  • 因为. 不是数字。 isdigit() 仅对包含 only 个数字的字符串返回 true。
  • 这在任何时候都不是真的,因为一件事不可能与另一件事在一起。
  • 但是“0.0”是一个浮点数,所以对我来说它也是一个数字还是不同?
  • "0.0" 不是数字。 "0" 是一个数字。 "0.0" 是一个包含两个数字和一个 "." 字符的字符串。参见dictionary.com/browse/digit,特别是定义3。
  • “数字”不代表“数字”

标签: python python-2.7 floating-point digit


【解决方案1】:

str.isdigit() 仅当字符串中的所有字符都是 数字 时才会返回 true。 . 是标点符号,而不是数字。

来自 Python 3 str.isdigit() documentation

通常,数字是具有属性值 Numeric_Type=Digit 或 Numeric_Type=Decimal 的字符

(对于 Python 2,对于 str 对象,仅考虑 ASCII 数字(09),但对于 unicode 对象,同样的定义适用。

official Numeric Property definitions specification;有 708 Unicode codepoints 符合该描述。

将此简化为一般的 unicode 类别,Unicode 中的数字类型有一个以 N 开头的类别,但 . 没有:

>>> import unicodedata
>>> unicodedata.category(u'.')
'Po'

P 在这里代表标点符号o 代表其他

反之亦然,仅包含数字的字符串并不总是可以转换为浮点数或数字:

>>> 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

【讨论】:

  • 是的,始终使用异常名称来捕获 except 块中的相应异常。 +1
猜你喜欢
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-02
  • 2022-12-19
  • 2013-09-18
  • 2022-08-14
相关资源
最近更新 更多