On 12/16/2012 11:19 PM, boB Stepp wrote:
int('10.0')
> Traceback (most recent call last): > File "<interactive input>", line 1, in <module> > ValueError: invalid literal for int() with base 10: '10.0' >>>> int("10") > 10 > > It is apparent that int() does not like strings with floating-point > formats. None of my books (as far as my flipping can tell) or the > below built-in help clarify this: > > > Help on int object: > > class int(object) > | int(x[, base]) -> integer > | > | Convert a string or number to an integer, if possible. A floating > | point argument will be truncated towards zero (this does not include a > | string representation of a floating point number!) When converting a > | string, use the optional base. It is an error to supply a base when > | converting a non-string. > > Of course if I type int(float('10.0')) I get the desired 10 . > > So, I am guessing that to convert strings to integers with int() that > the string must already be of integer format? What is the rationale > for setting up int() in this manner? > > Thanks as I continue to puzzle over the fine points of the basics... > boB
What would you want to happen for int("10.5")? If 10.0 was accepted, it would be consistent to accept 10.5, too. The issue, I think, is that a simple operation should not go too far beyond what it is supposed to do - if you are sure you are converting a float in a string, you need to do it explicitly, and if you're converting a string to an int and the string is not actually an int, then maybe it wasn't supposed to be a float and it's a mistake in the program -- and therefore python should alert you. -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor