Python将字符串转换为int或float,哪个是可取的?

发布于 2025-02-13 16:49:09 字数 1394 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

格子衫的從容 2025-02-20 16:49:09

如有疑问,您应该将str转换为float,因为它能够处理更通用的输入,例如,

float("1.2")
>1.2

转换尝试到整数抛出时valueerror

int("1.2")
>ValueError: invalid literal for int() with base 10: '1.2'

即,这确实取决于手头的问题。此外,您应该问自己,为什么需要将str转换为要开始的数字。可能会遇到的数据预处理的初步步骤可能是不正确的。将字符串转换为一个数字似乎更像是试图撤消以前/其他人遇到的错误。

When in doubt, you should convert the str to a float as it is able to handle a more general input, e.g.

float("1.2")
>1.2

while the conversion attempt to an integer throws a ValueError, i.e.

int("1.2")
>ValueError: invalid literal for int() with base 10: '1.2'

However, it truly depends on the problem at hand. Moreover, you should ask yourself why there is a need to convert a str to a number to begin with. Likely, there is a preliminary step in the data pre-processing that might have been mishandled. Converting a string to a number seems more like an attempt to undo a mistake done earlier/by someone else.

明天过后 2025-02-20 16:49:09

该规则是“转换为INT,除非另有需要”。

整数类型是最好的,因为它的空间较小。因此,如果您可以使用整数,请使用它。如果不是,请使用浮点。 (但将使用更多内存)

当您需要准确的值时,使用浮点。

The rule is "Convert to int unless otherwise is needed."

Integer type is the best one mainly as it has less space. So if you can use integer, use it. If not, use float. (but more memory will be used)

Float is used when you need accurate values.

拍不死你 2025-02-20 16:49:09

这取决于您要转换的数据以及您需要的内容。
如果数据由连续数值组成,则您可能需要转换为float。如果数据是由数值谨慎值制成的,则可以使用int

本文可能会有所帮助

It depends on the data you are converting and what you need it for.
If the data is composed of continuous numerical values, then you probably will want to convert to float. If the data is made of numerical discreet values, then you're probably ok to use int.

This article may be helpful

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文