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.
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.
发布评论
评论(3)
如有疑问,您应该将
str
转换为float
,因为它能够处理更通用的输入,例如,转换尝试到整数抛出
时valueerror
,即,这确实取决于手头的问题。此外,您应该问自己,为什么需要将
str
转换为要开始的数字。可能会遇到的数据预处理的初步步骤可能是不正确的。将字符串转换为一个数字似乎更像是试图撤消以前/其他人遇到的错误。When in doubt, you should convert the
str
to afloat
as it is able to handle a more general input, e.g.while the conversion attempt to an integer throws a
ValueError
, i.e.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.该规则是“转换为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.
这取决于您要转换的数据以及您需要的内容。
如果数据由连续数值组成,则您可能需要转换为
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 useint
.This article may be helpful