From the documentation :
If x is not a number or a base value is given, then x must be a string or a Unicode object representing an integer literal in the base ...
Obviously, "1.7" does not represent an integer literal in the base base.
If you want to know why the python developer decided to limit himself to integer literals in the radix base, there are an infinite number of reasons, and you will have to ask Guido et. to know for sure. One of them is ease of implementation + efficiency. You might think that it would be easy for them to implement it as:
- Interpret the number as floating
- truncate integer
Unfortunately, this does not work in python, since integers can have arbitrary precision, but float cannot. Large numbers of special enclosures can lead to inefficiency for general case 1 .
In addition, forceful execution of int(float(...)) has the added benefit of clarity - this makes it more obvious what the input line looks like, which can help debug elsewhere. In fact, I can argue that even if int would accept strings like "1.7" , it would be better to write int(float("1.7")) in any case to increase the clarity of the code.
1 Assuming some verification. Other languages ​​overlook this - for example. ruby will evaluate '1e6'.to_i and give you 1 , since it ceases to deal with the first non-integral character. It seems like this could lead to funny tracking errors ...
mgilson
source share