Re: pre-check for string-to-number conversion
From: Steven Bethard (steven.bethard_at_gmail.com)
Date: 02/12/05
- Next message: Philippe C. Martin: "dos box appears when clicking .pyc"
- Previous message: Michael Hartl: "Re: check if object is number"
- Next in thread: Michael Hoffman: "Re: pre-check for string-to-number conversion"
- Maybe reply: Michael Hoffman: "Re: pre-check for string-to-number conversion"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: Philippe C. Martin: "dos box appears when clicking .pyc"
- Previous message: Michael Hartl: "Re: check if object is number"
- Next in thread: Michael Hoffman: "Re: pre-check for string-to-number conversion"
- Maybe reply: Michael Hoffman: "Re: pre-check for string-to-number conversion"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|