Counterintuitive behaviour of int() in python
It's clearly stated in the docs that int(number) is a flooring type conversion:
and int(string) returns an int if and only if the string is an integer literal.
int('1.23') ValueError int('1') 1
Is there any special reason for that? I find it counterintuitive that the function floors in one case, but not the other.
int(some_string) is an explicit request to convert a string to integer format; the rules for this conversion specify that the string must contain a valid integer literal representation.
int(float) is an explicit request to convert a float to an integer; the rules for this conversion specify that the float's fractional portion will be truncated.
In order for
int("3.1459") to return
3 the interpreter would have to implicitly convert the string to a float. Since Python doesn't support implicit conversions, it chooses to raise an exception instead.
★ Back to homepage or read more recommendations: