在Python中将对象转换为浮点数存在问题。

huangapple go评论55阅读模式
英文:

Issue with converting object to float in Python

问题

遇到了将对象转换为浮点数的问题。我有一个包含以对象形式存储的数值的变量。然而,当我尝试使用float()函数将其转换为浮点数时,我收到了一个错误消息。以下是我的代码示例:

value = "3.14"
float_value = float(value)

我收到的错误消息是:

ValueError: 无法将字符串转换为浮点数:'3.14'

我已经验证了该值是有效浮点数的字符串表示。可能是什么原因导致了这个错误,我如何成功地将对象转换为浮点数?

英文:

I am working on a Python project and encountered an issue with converting an object to a float. I have a variable that contains a numeric value stored as an object. However, when I try to convert it to a float using the float() function, I get an error. Here's a sample of my code:

value = "3.14"
float_value = float(value)

The error message I receive is:

ValueError: could not convert string to float: '3.14'

I have verified that the value is a string representation of a valid float. What could be causing this error, and how can I successfully convert the object to a float?

答案1

得分: 1

你可以按照以下方式模拟这个问题:

value = '3․14'
float(value)

这将生成:

ValueError: could not convert string to float: '3․14'

你需要复制粘贴这里显示的代码 - 即不要重新输入。

这里的问题是看起来像一个句点的东西并不是你想象的那样。实际上,它是 '\u2024',是一个 Unicode 的 One Dot Leader。

英文:

You can emulate this problem as follows:

value = '3․14'
float(value)

This will generate:

ValueError: could not convert string to float: '3․14'

You will need to copy'n'paste the code shown here - i.e., don't re-type it.

The issue here is that what looks like a Full Stop isn't what you think it is. It's actually '\u2024' which is a Unicode One Dot Leader

huangapple
  • 本文由 发表于 2023年7月11日 02:42:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定