pre-check for string-to-number conversion

1

18k11tm001

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. I would like
to simply perform a pre-check before I do the conversion, but I can't
figure out how to do it. I see that strings have a function called
isdigit(), but that simply checks whether all characters in the string
are digits -- not what I need. Any suggestions? Thanks.
 
S

Steven Bethard

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,219
Messages
2,571,118
Members
47,737
Latest member
CarleyHarm

Latest Threads

Top