Counterintuitive behaviour of int() in python

It's clearly stated in the docs that int(number) is a flooring type conversion:

    int(1.23)
    1

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.

There is no special reason. Python is simply applying its general principle of not performing implicit conversions, which are well-known causes of problems, particularly for newcomers, in languages such as Perl and Javascript.

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.

From: stackoverflow.com/q/36085185

Back to homepage or read more recommendations: