Python3.6 将字符串转换为浮点数 - 错误或功能?
Python3.6 cast string to float - bug or feature?
我正在处理字符串并从中提取浮点数,浮点数可以位于字符串中的不同位置。然后我注意到 Python 版本 2.7 和 3.6 之间的不同行为。例如,包含非数字文字的字符串,例如 _
以下是我发现的摘要:
Python 2.7:
In [3]: float('0_001')
ValueError: invalid literal for float(): 0_001
In [4]:
Python 3.6:
In [16]: float( '0_001' )
Out[16]: 1.0
我期望演员表的行为与 2.7 版本一致,并且由于 0_001
和 1.0
之间的距离很宽,我怀疑这是3.6版本,但我可能错了。
如果我用其他任何东西替换 3.6 版中的 _
文字,例如- * ,
等。我得到了预期的 ValueError:
.
如果这不是一个错误,而是一个功能,有人可以向我解释为什么这样的转换是有效的吗?
Python 2.7版本:
Python 2.7.16 (default, Apr 6 2019, 01:42:57)
IPython 5.8.0 -- An enhanced Interactive Python.
Python 3.6版本:
Python 3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 19:07:31)
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
编辑:
根据 Sach 的回答,这是 v3.6 的实际功能,但我仍然不明白这是为什么?它有什么用途?
In [2]: float( '0.0_1_2_3_4' )
Out[2]: 0.01234
从源代码1 and 2,你可以看到下划线的具体处理,同时从字符串转换浮点数。
这在 2.7 中不存在,是从 3.6 添加的
它检查下划线是否存在,后跟以下条件。
- 只能在数字后使用下划线。
- 只能在数字前使用下划线。
- 末尾不允许有下划线。
PEP515 应该包含您正在寻找的答案。
This PEP proposes to extend Python's syntax and number-from-string
constructors so that underscores can be used as visual separators for
digit grouping purposes in integral, floating-point and complex number
literals.
This is a common feature of other modern languages, and can aid
readability of long literals, or literals whose value should clearly
separate into parts, such as bytes or words in hexadecimal notation.
它还描述了使用它们的规则。
我正在处理字符串并从中提取浮点数,浮点数可以位于字符串中的不同位置。然后我注意到 Python 版本 2.7 和 3.6 之间的不同行为。例如,包含非数字文字的字符串,例如 _
以下是我发现的摘要:
Python 2.7:
In [3]: float('0_001')
ValueError: invalid literal for float(): 0_001
In [4]:
Python 3.6:
In [16]: float( '0_001' )
Out[16]: 1.0
我期望演员表的行为与 2.7 版本一致,并且由于 0_001
和 1.0
之间的距离很宽,我怀疑这是3.6版本,但我可能错了。
如果我用其他任何东西替换 3.6 版中的 _
文字,例如- * ,
等。我得到了预期的 ValueError:
.
如果这不是一个错误,而是一个功能,有人可以向我解释为什么这样的转换是有效的吗?
Python 2.7版本:
Python 2.7.16 (default, Apr 6 2019, 01:42:57)
IPython 5.8.0 -- An enhanced Interactive Python.
Python 3.6版本:
Python 3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 19:07:31)
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
编辑: 根据 Sach 的回答,这是 v3.6 的实际功能,但我仍然不明白这是为什么?它有什么用途?
In [2]: float( '0.0_1_2_3_4' )
Out[2]: 0.01234
从源代码1 and 2,你可以看到下划线的具体处理,同时从字符串转换浮点数。
这在 2.7 中不存在,是从 3.6 添加的
它检查下划线是否存在,后跟以下条件。
- 只能在数字后使用下划线。
- 只能在数字前使用下划线。
- 末尾不允许有下划线。
PEP515 应该包含您正在寻找的答案。
This PEP proposes to extend Python's syntax and number-from-string constructors so that underscores can be used as visual separators for digit grouping purposes in integral, floating-point and complex number literals.
This is a common feature of other modern languages, and can aid readability of long literals, or literals whose value should clearly separate into parts, such as bytes or words in hexadecimal notation.
它还描述了使用它们的规则。