pre-check for string-to-number conversion

Steven Bethard steven.bethard at gmail.com
Fri Feb 11 18:26:02 EST 2005


18k11tm001 at 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




More information about the Python-list mailing list