Convert '165.0' to int

Frank Millman frank at chagford.com
Sat Jul 23 11:08:17 CEST 2011


On Jul 23, 10:23 am, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:
> Frank Millman wrote:
> > To recap, the original problem is that it would appear that some third-
> > party systems, when serialising int's into a string format, add a .0
> > to the end of the string. I am trying to get back to the original int
> > safely.
>
> > The ideal solution is the one I sketched out earlier - modify python's
> > 'int' function to accept strings such as '165.0'.
>
> > Do you think this would get any traction if I proposed it? Or would it
> > fall foul of the moratorium?
>
> No, and no. It would not get any traction -- indeed, many people, including
> myself, would oppose it. And it would not fall foul of the moratorium,
> because that is over.
>
> I can only point you to what I wrote in reference to somebody else's idea
> that changing Python was the most "convenient solution":
>
> http://www.mail-archive.com/python-list%40python.org/msg315552.html
>
> Python is a general purpose programming language. If int("1.0") does not do
> what you want, write a function that does, and use it instead! You said
> that you want a function that ignores a trailing .0 but warns you if
> there's some other decimal value. Easy:
>
> def my_int(astring):
>     # Untested
>     if astring.endswith(".0"):
>         astring = astring[:-2]
>     return int(astring)
>
> my_int("165.0") will return 165, as expected, while still raising an
> exception for float values "165.1" or "165.1E9".
>
> 90% of programming is deciding *precisely* what behaviour you want. Once
> you've done that, the rest is easy.
>
> Apart from debugging and writing documentation and making it fast enough,
> which is the other 90%.
>
> *wink*
>
> --
> Steven

No argument with any of that.

Frank



More information about the Python-list mailing list