Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10013 > unrolled thread

Re: Convert '165.0' to int

Started byLeo Jay <python.leojay@gmail.com>
First post2011-07-21 17:47 +0800
Last post2011-07-25 10:19 +0200
Articles 20 on this page of 50 — 15 participants

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Convert '165.0' to int Leo Jay <python.leojay@gmail.com> - 2011-07-21 17:47 +0800
    Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-21 04:05 -0700
      Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-21 04:23 -0700
    Re: Convert '165.0' to int Web Dreamer <webdreamer@nospam.fr> - 2011-07-21 14:46 +0200
      Re: Convert '165.0' to int Billy Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com> - 2011-07-21 09:27 -0400
        Re: Convert '165.0' to int Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-07-22 04:40 +0200
          Re: Convert '165.0' to int Billy Mays <noway@nohow.com> - 2011-07-22 00:45 -0400
            Re: Convert '165.0' to int Grant Edwards <invalid@invalid.invalid> - 2011-07-22 14:21 +0000
              Re: Convert '165.0' to int Billy Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com> - 2011-07-22 10:49 -0400
                Re: Convert '165.0' to int Grant Edwards <invalid@invalid.invalid> - 2011-07-22 14:58 +0000
                  Re: Convert '165.0' to int Billy Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com> - 2011-07-22 11:06 -0400
                    Re: Convert '165.0' to int Grant Edwards <invalid@invalid.invalid> - 2011-07-22 15:44 +0000
            Re: Convert '165.0' to int Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-07-24 10:03 +0200
        Re: Convert '165.0' to int Web Dreamer <webdreamer@nospam.fr> - 2011-07-25 10:23 +0200
          Re: Convert '165.0' to int Web Dreamer <webdreamer@nospam.fr> - 2011-07-25 11:00 +0200
      Re: Convert '165.0' to int Grant Edwards <invalid@invalid.invalid> - 2011-07-21 14:13 +0000
        Re: Convert '165.0' to int Terry Reedy <tjreedy@udel.edu> - 2011-07-21 16:00 -0400
          Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-21 22:55 -0700
            Re: Convert '165.0' to int Hrvoje Niksic <hniksic@xemacs.org> - 2011-07-22 14:42 +0200
              Re: Convert '165.0' to int rantingrick <rantingrick@gmail.com> - 2011-07-22 12:32 -0700
                Re: Convert '165.0' to int rantingrick <rantingrick@gmail.com> - 2011-07-22 12:34 -0700
                Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-23 06:06 +1000
            Re: Convert '165.0' to int Terry Reedy <tjreedy@udel.edu> - 2011-07-22 15:59 -0400
              Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-22 23:53 -0700
                Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-23 17:42 +1000
                  Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-23 02:03 -0700
                  Re: Convert '165.0' to int Billy Mays <noway@nohow.com> - 2011-07-23 11:12 -0400
                    Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-24 01:20 +1000
                    Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-23 23:53 -0700
                      Re: Convert '165.0' to int Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-24 17:34 +1000
                        Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-24 00:58 -0700
                          Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-24 18:07 +1000
                            Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-24 01:21 -0700
                              Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-24 18:28 +1000
                Re: Convert '165.0' to int Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-23 18:23 +1000
                  Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-23 02:08 -0700
                Re: Convert '165.0' to int rantingrick <rantingrick@gmail.com> - 2011-07-23 11:28 -0700
                  Re: Convert '165.0' to int Billy Mays <noway@nohow.com> - 2011-07-23 23:53 -0400
                    Re: Convert '165.0' to int Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-24 17:21 +1000
                      Re: Convert '165.0' to int Ben Finney <ben+python@benfinney.id.au> - 2011-07-24 17:43 +1000
                  Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-24 01:36 -0700
                    Re: Convert '165.0' to int Ben Finney <ben+python@benfinney.id.au> - 2011-07-24 18:53 +1000
                      Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-24 02:01 -0700
                        Re: Convert '165.0' to int Ben Finney <ben+python@benfinney.id.au> - 2011-07-24 19:25 +1000
                      Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-24 19:42 +1000
                    Re: Convert '165.0' to int Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2011-07-25 12:04 +1200
                      Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-24 22:50 -0700
                        RE: Convert '165.0' to int "Prasad, Ramit" <ramit.prasad@jpmorgan.com> - 2011-08-01 20:42 -0400
                      RE: Convert '165.0' to int "Prasad, Ramit" <ramit.prasad@jpmorgan.com> - 2011-08-01 20:32 -0400
              Re: Convert '165.0' to int Web Dreamer <webdreamer@nospam.fr> - 2011-07-25 10:19 +0200

Page 2 of 3 — ← Prev page 1 [2] 3  Next page →


#10142

Fromrantingrick <rantingrick@gmail.com>
Date2011-07-22 12:34 -0700
Message-ID<e0fd6dba-5dbb-4d13-af52-dd06fef722df@a31g2000vbt.googlegroups.com>
In reply to#10140
On Jul 22, 2:32 pm, rantingrick <rantingr...@gmail.com> wrote:
> >>> '{0:,.0f}'.format(2**53)
> '9,007,199,254,740,992'

Would have been better to say

>>> '{0:,}'.format(2**53)
'9,007,199,254,740,992'

[toc] | [prev] | [next] | [standalone]


#10150

FromChris Angelico <rosuav@gmail.com>
Date2011-07-23 06:06 +1000
Message-ID<mailman.1388.1311365195.1164.python-list@python.org>
In reply to#10140
On Sat, Jul 23, 2011 at 5:32 AM, rantingrick <rantingrick@gmail.com> wrote:
> That's nine-quadrillion people! Only for galactic measurements or
> microscopic reasons would you need such large numbers.
>

Never decide that "nobody would need numbers bigger than X". Someone
will. One common thing to do with big numbers is to use the pieces
separately; although I would never recommend floating point for
encoded numbers like that. But I quite happily treat BIND serial
numbers as straightforward integers, and they're usually something
like 2011072203 for the 3rd change on the 22nd of July 2011. That's a
fairly small example (in fact, BIND requires that serial numbers fit
inside a 32-bit integer, IIRC), but there are plenty of other examples
of numbers that get big fast because of that sort of thing.

ChrisA

[toc] | [prev] | [next] | [standalone]


#10147

FromTerry Reedy <tjreedy@udel.edu>
Date2011-07-22 15:59 -0400
Message-ID<mailman.1387.1311364775.1164.python-list@python.org>
In reply to#10073
On 7/22/2011 1:55 AM, Frank Millman wrote:

> As the OP, I will clarify what *my* requirement is. This discussion
> has gone off at various tangents beyond what I was asking for.

Typical. Don't worry about it ;-).

> As suggested above, I am only talking about a string containing int
> literals followed by '.' followed by zero or more zeros.

> int(float(x)) does the job,

Not given that specification.

 >>> s='123456789012345678901.0'
 >>> int(float(s))
123456789012345683968

> and I am happy with that.

You should only be if you add 'with fewer than 18 digits' after 'int 
literals' to your spec.

> I was just asking if there were any alternatives.

 >>> int(s.split('.')[0])
123456789012345678901


-- 
Terry Jan Reedy

[toc] | [prev] | [next] | [standalone]


#10166

FromFrank Millman <frank@chagford.com>
Date2011-07-22 23:53 -0700
Message-ID<4230ed8b-5173-4408-938f-3777dcd60588@t7g2000vbv.googlegroups.com>
In reply to#10147
On Jul 22, 9:59 pm, Terry Reedy <tjre...@udel.edu> wrote:
> On 7/22/2011 1:55 AM, Frank Millman wrote:
>
> > As the OP, I will clarify what *my* requirement is. This discussion
> > has gone off at various tangents beyond what I was asking for.
>
> Typical. Don't worry about it ;-).
>
> > As suggested above, I am only talking about a string containing int
> > literals followed by '.' followed by zero or more zeros.
> > int(float(x)) does the job,
>
> Not given that specification.
>
>  >>> s='123456789012345678901.0'
>  >>> int(float(s))
> 123456789012345683968
>
> > and I am happy with that.
>
> You should only be if you add 'with fewer than 18 digits' after 'int
> literals' to your spec.
>
> > I was just asking if there were any alternatives.
>
>  >>> int(s.split('.')[0])
> 123456789012345678901
>

The problem with that is that it will silently ignore any non-zero
digits after the point. Of course int(float(x)) does the same, which I
had overlooked.

I do not expect any non-zero digits after the point, but if there are,
I would want to be warned, as I should probably be treating it as a
float, not an int.

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?

Frank

[toc] | [prev] | [next] | [standalone]


#10167

FromChris Angelico <rosuav@gmail.com>
Date2011-07-23 17:42 +1000
Message-ID<mailman.1398.1311406954.1164.python-list@python.org>
In reply to#10166
On Sat, Jul 23, 2011 at 4:53 PM, Frank Millman <frank@chagford.com> wrote:
> The problem with that is that it will silently ignore any non-zero
> digits after the point. Of course int(float(x)) does the same, which I
> had overlooked.

If you know that there will always be a trailing point, you can trim
off any trailing 0s, then trim off a trailing '.', and then cast to
int:

int(s.rstrip('0').rstrip('.'))

It'll remove only zeroes and then only periods, as opposed to
s.rstrip('.0') which would give a wrong result for (say) '40.000', so
this should be safe. If there's any non-zero digits after the decimal,
they and the decimal will be kept, which will cause the int() cast to
throw an exception.

ChrisA

[toc] | [prev] | [next] | [standalone]


#10170

FromFrank Millman <frank@chagford.com>
Date2011-07-23 02:03 -0700
Message-ID<eda87c95-97ee-4b34-ac8a-956f6e0ee233@r18g2000vbs.googlegroups.com>
In reply to#10167
On Jul 23, 9:42 am, Chris Angelico <ros...@gmail.com> wrote:
> On Sat, Jul 23, 2011 at 4:53 PM, Frank Millman <fr...@chagford.com> wrote:
> > The problem with that is that it will silently ignore any non-zero
> > digits after the point. Of course int(float(x)) does the same, which I
> > had overlooked.
>
> If you know that there will always be a trailing point, you can trim
> off any trailing 0s, then trim off a trailing '.', and then cast to
> int:
>
> int(s.rstrip('0').rstrip('.'))
>

I like it. 100% solution to the problem, and neater than the
alternatives.

Thanks

Frank

[toc] | [prev] | [next] | [standalone]


#10173

FromBilly Mays <noway@nohow.com>
Date2011-07-23 11:12 -0400
Message-ID<j0eocp$msk$1@speranza.aioe.org>
In reply to#10167
On 7/23/2011 3:42 AM, Chris Angelico wrote:
>
> int(s.rstrip('0').rstrip('.'))
>

Also, it will (in?)correct parse strings such as:

'165............00000000000000'

to 165.

--
Bill

[toc] | [prev] | [next] | [standalone]


#10174

FromChris Angelico <rosuav@gmail.com>
Date2011-07-24 01:20 +1000
Message-ID<mailman.1401.1311434438.1164.python-list@python.org>
In reply to#10173
On Sun, Jul 24, 2011 at 1:12 AM, Billy Mays <noway@nohow.com> wrote:
> On 7/23/2011 3:42 AM, Chris Angelico wrote:
>>
>> int(s.rstrip('0').rstrip('.'))
>>
>
> Also, it will (in?)correct parse strings such as:
>
> '165............00000000000000'
>
> to 165.

Yes, it will, but is that an issue to the OP? Programming is about
solving the problem you have, not the problems you don't have.
Sometimes it's better to have a simple solution that does the job than
an extremely complex one that isn't excessively lenient. Is it such a
problem for it to be lenient?

ChrisA

[toc] | [prev] | [next] | [standalone]


#10186

FromFrank Millman <frank@chagford.com>
Date2011-07-23 23:53 -0700
Message-ID<ff5b41ab-1361-41ad-b8d6-0bab70be017d@x10g2000vbl.googlegroups.com>
In reply to#10173
On Jul 23, 5:12 pm, Billy Mays <no...@nohow.com> wrote:
> On 7/23/2011 3:42 AM, Chris Angelico wrote:
>
>
>
> > int(s.rstrip('0').rstrip('.'))
>
> Also, it will (in?)correct parse strings such as:
>
> '165............00000000000000'
>
> to 165.
>
> --
> Bill

True enough.

If I really wanted to be 100% safe, how about this -

    def get_int(s):
        if '.' in s:
            num, dec = s.split('.', 1)
            if dec != '':
                if int(dec) != 0:
                    raise ValueError('Invalid literal for int')
            return int(num)
        return int(s)

Frank

[toc] | [prev] | [next] | [standalone]


#10189

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2011-07-24 17:34 +1000
Message-ID<4e2bcaf5$0$30004$c3e8da3$5496439d@news.astraweb.com>
In reply to#10186
Frank Millman wrote:

> If I really wanted to be 100% safe, how about this -
> 
>     def get_int(s):
>         if '.' in s:
>             num, dec = s.split('.', 1)
>             if dec != '':
>                 if int(dec) != 0:
>                     raise ValueError('Invalid literal for int')
>             return int(num)
>         return int(s)

Consider what happens if you pass s = "42.-0".


-- 
Steven

[toc] | [prev] | [next] | [standalone]


#10191

FromFrank Millman <frank@chagford.com>
Date2011-07-24 00:58 -0700
Message-ID<1a5604c3-764d-40e1-a063-b05f8729864d@y13g2000yqy.googlegroups.com>
In reply to#10189
On Jul 24, 9:34 am, Steven D'Aprano <steve
+comp.lang.pyt...@pearwood.info> wrote:
> Frank Millman wrote:
> > If I really wanted to be 100% safe, how about this -
>
> >     def get_int(s):
> >         if '.' in s:
> >             num, dec = s.split('.', 1)
> >             if dec != '':
> >                 if int(dec) != 0:
> >                     raise ValueError('Invalid literal for int')
> >             return int(num)
> >         return int(s)
>
> Consider what happens if you pass s = "42.-0".
>

Grrrr!

Ok, what if I change
    if int(dec) != 0:
to
    if [_ for _ in list(dec) if _ != '0']:

If I do this, I can get rid of the previous line -
    if dec != ''

Am I getting closer?

Frank

[toc] | [prev] | [next] | [standalone]


#10193

FromChris Angelico <rosuav@gmail.com>
Date2011-07-24 18:07 +1000
Message-ID<mailman.1413.1311494862.1164.python-list@python.org>
In reply to#10191
On Sun, Jul 24, 2011 at 5:58 PM, Frank Millman <frank@chagford.com> wrote:
>  if int(dec) != 0:
> to
>    if [_ for _ in list(dec) if _ != '0']:
>

if dec.rtrim('0')!='':

ChrisA

[toc] | [prev] | [next] | [standalone]


#10194

FromFrank Millman <frank@chagford.com>
Date2011-07-24 01:21 -0700
Message-ID<65761f82-3f69-4a0c-8159-72e709dd87fe@cq10g2000vbb.googlegroups.com>
In reply to#10193
On Jul 24, 10:07 am, Chris Angelico <ros...@gmail.com> wrote:
> On Sun, Jul 24, 2011 at 5:58 PM, Frank Millman <fr...@chagford.com> wrote:
> >  if int(dec) != 0:
> > to
> >    if [_ for _ in list(dec) if _ != '0']:
>
> if dec.rtrim('0')!='':
>
> ChrisA

I think you meant 'rstrip', but yes, neater and faster.

Thanks

Frank

[toc] | [prev] | [next] | [standalone]


#10195

FromChris Angelico <rosuav@gmail.com>
Date2011-07-24 18:28 +1000
Message-ID<mailman.1414.1311496091.1164.python-list@python.org>
In reply to#10194
On Sun, Jul 24, 2011 at 6:21 PM, Frank Millman <frank@chagford.com> wrote:
> On Jul 24, 10:07 am, Chris Angelico <ros...@gmail.com> wrote:
>> if dec.rtrim('0')!='':
>>
>> ChrisA
>
> I think you meant 'rstrip', but yes, neater and faster.
>
> Thanks

Yeah, I did. Mea culpa... every language has it somewhere, but I keep
mucking up which one calls it what. That's what I get for not flicking
to IDLE before posting!

ChrisA

[toc] | [prev] | [next] | [standalone]


#10168

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2011-07-23 18:23 +1000
Message-ID<4e2a84fb$0$29973$c3e8da3$5496439d@news.astraweb.com>
In reply to#10166
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

[toc] | [prev] | [next] | [standalone]


#10171

FromFrank Millman <frank@chagford.com>
Date2011-07-23 02:08 -0700
Message-ID<b5d40ccf-f4d8-498f-ae64-2fe7c1ec4734@p20g2000yqp.googlegroups.com>
In reply to#10168
On Jul 23, 10:23 am, Steven D'Aprano <steve
+comp.lang.pyt...@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

[toc] | [prev] | [next] | [standalone]


#10176

Fromrantingrick <rantingrick@gmail.com>
Date2011-07-23 11:28 -0700
Message-ID<3d6b3ab4-6682-4e33-ab03-098d2f82c20d@o18g2000yqm.googlegroups.com>
In reply to#10166
On Jul 23, 1:53 am, Frank Millman <fr...@chagford.com> wrote:
>--------------------------------------------------
> The problem with that is that it will silently ignore any non-zero
> digits after the point. Of course int(float(x)) does the same, which I
> had overlooked.
>--------------------------------------------------

Wait a minute; first you said all you wanted was to cast "string
floats" to integers NOW your changing the rules.

>--------------------------------------------------
> I do not expect any non-zero digits after the point, but if there are,
> I would want to be warned, as I should probably be treating it as a
> float, not an int.
>--------------------------------------------------
Then the solution is a try:except.

py> def castit(value):
...     try:
...         v = int(value)
...         return v
...     except ValueError:
...         return float(value)
...
py> castit('165')
165
py> castit('165.0')
165.0
py> castit('165.333')
165.333
py> castit('3.3')
3.3

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

But you also said you wanted floats too, i am confused??

>--------------------------------------------------
> The ideal solution is the one I sketched out earlier - modify python's
> 'int' function to accept strings such as '165.0'.
>--------------------------------------------------

NO! You create your OWN casting function for special cases.

PythonZEN: "Special cases aren't special enough to break the rules."

[toc] | [prev] | [next] | [standalone]


#10183

FromBilly Mays <noway@nohow.com>
Date2011-07-23 23:53 -0400
Message-ID<j0g50r$uai$1@speranza.aioe.org>
In reply to#10176
On 7/23/2011 2:28 PM, rantingrick wrote:
>
> On Jul 23, 1:53 am, Frank Millman<fr...@chagford.com>  wrote:
>> --------------------------------------------------
>> The problem with that is that it will silently ignore any non-zero
>> digits after the point. Of course int(float(x)) does the same, which I
>> had overlooked.
>> --------------------------------------------------
>
> Wait a minute; first you said all you wanted was to cast "string
> floats" to integers NOW your changing the rules.
>
>> --------------------------------------------------
>> I do not expect any non-zero digits after the point, but if there are,
>> I would want to be warned, as I should probably be treating it as a
>> float, not an int.
>> --------------------------------------------------
> Then the solution is a try:except.
>
> py>  def castit(value):
> ...     try:
> ...         v = int(value)
> ...         return v
> ...     except ValueError:
> ...         return float(value)
> ...
> py>  castit('165')
> 165
> py>  castit('165.0')
> 165.0
> py>  castit('165.333')
> 165.333
> py>  castit('3.3')
> 3.3
>
>> --------------------------------------------------
>> 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.
>> --------------------------------------------------
>
> But you also said you wanted floats too, i am confused??
>
>> --------------------------------------------------
>> The ideal solution is the one I sketched out earlier - modify python's
>> 'int' function to accept strings such as '165.0'.
>> --------------------------------------------------
>
> NO! You create your OWN casting function for special cases.
>
> PythonZEN: "Special cases aren't special enough to break the rules."

I'll probably get flak for this, but damn the torpedoes:

def my_int(num):
     import re
     try:
         m = re.match('^(-?[0-9]+)(.0)?$', num)
         return int(m.group(1))
     except AttributeError:
         #raise your own error, or re raise
         raise


--
Bill

[toc] | [prev] | [next] | [standalone]


#10187

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2011-07-24 17:21 +1000
Message-ID<4e2bc7f3$0$29976$c3e8da3$5496439d@news.astraweb.com>
In reply to#10183
Billy Mays wrote:

> I'll probably get flak for this, but damn the torpedoes:
> 
> def my_int(num):
>      import re
>      try:
>          m = re.match('^(-?[0-9]+)(.0)?$', num)
>          return int(m.group(1))

As a toy for learning about regexes, that's fine, but I trust you would
never use that in production. There are less verbose ways of wasting time
and memory.


>      except AttributeError:
>          #raise your own error, or re raise
>          raise

"except Foo: raise" is pointless; a bare raise is only useful if you need to
do something before, or instead of, re-raising the current exception.

try:
    boil(kettle)
except HeatingError:
    if isempty(kettle):
        kettle.fill(water)
        boil(kettle)
    else:
        raise


Catching an exception only to unconditionally re-raise it is only good for
generating more heat in the CPU and making other developers laugh at you :)



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#10190

FromBen Finney <ben+python@benfinney.id.au>
Date2011-07-24 17:43 +1000
Message-ID<878vrorunc.fsf@benfinney.id.au>
In reply to#10187
Steven D'Aprano <steve+comp.lang.python@pearwood.info> writes:

> As a toy for learning about regexes, that's fine, but I trust you would
> never use that in production. There are less verbose ways of wasting time
> and memory.

+1 QotW

-- 
 \         “I may disagree with what you say, but I will defend to the |
  `\        death your right to mis-attribute this quote to Voltaire.” |
_o__)                   —Avram Grumer, rec.arts.sf.written, 2000-05-30 |
Ben Finney

[toc] | [prev] | [next] | [standalone]


Page 2 of 3 — ← Prev page 1 [2] 3  Next page →

Back to top | Article view | comp.lang.python


csiph-web