Re: pre-check for string-to-number conversion

From: Steven Bethard (steven.bethard_at_gmail.com)
Date: 02/12/05


Date: Fri, 11 Feb 2005 16:26:02 -0700

18k11tm001@sneakemail.com wrote:
> I am reading an ASCII data file and converting some of the strings to
> integers or floats. However, some of the data is corrupted and the
> conversion doesn't work. I know that I can us exceptions, but they
> don't seem like the cleanest and simplest solution to me.

You should reconsider this thought. It's quite clean and fast:

for s in get_ASCII_strings_from_data_file():
     try:
         f = float(s)
     except ValueError:
         do_whatever_you_need_to_do_for_invalid_data()

> I would like to simply perform a pre-check before I do the
> conversion, but I can't figure out how to do it.

Again, this is the less Pythonic approach, but one option would be to
use regular expressions:

matcher = re.compile(r'[\d.]+')
for s in get_ASCII_strings_from_data_file():
     if matcher.match(s):
         f = float(s)
     else:
         do_whatever_you_need_to_do_for_invalid_data()

but note that this won't except valid floats like '1e10'. You'll also
note that this is actually less concise than the exception based approach.

Steve



Relevant Pages

  • Re: Why I dont believe in static typing
    ... >> Yes, and it will even explain you why it does so, because the type checker ... Write the library, and you can have base 10 floats, ... just type in the conversion function (or maybe use a conversion ... The point I am trying to make is that it doesn't hurt as much as you ...
    (comp.lang.lisp)
  • Re: Is this the Right way TO release COM interface ?
    ... COM compiler support wrappers actually preserve ... It's not so clean to undo the conversion. ... changing the retval parameter to the return type and adding exceptions, then absolutely use the wrapper classes. ... Are you saying that there's an option to request #import to generate code that doesn't translate HRESULTs into exceptions? ...
    (microsoft.public.vc.language)
  • Re: Contracted exceptions for Ada
    ... the conversion to the fixed-point type _Whatever_ cannot ... Therefore we do not need to handle exceptions for this ... conversion, so we will not do any ... would not make the same mistake while porting the compiler... ...
    (comp.lang.ada)
  • Re: Contracted exceptions for Ada
    ... "The maximum horizontal velocity is ... Therefore the conversion to the fixed-point type _Whatever_ ... do any extra processing to avoid exceptions." ...
    (comp.lang.ada)
  • Re: Identifying an exact binary representation
    ... on conversion to floats. ... digits after the decimal point in its exact decimal representation. ... IEEE single ...
    (comp.lang.fortran)