[Tutor] Limitation of int() in converting strings

boB Stepp robertvstepp at gmail.com
Mon Dec 17 05:19:26 CET 2012


>>> 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


More information about the Tutor mailing list