Numeric Conversion
Justin Sheehy
dworkin at ccs.neu.edu
Thu Dec 9 10:50:10 EST 1999
Iddo Friedberg <idoerg at cc.huji.ac.il> writes:
> My problem: I have text files with fields which are either numeric, or
> not. I'd like to convert the numeric ones into numerical values, while
> keeping the rest as strings. I initially did that by trapping the
> exceptions that atoi() & atol() generate upon hitting a non-numeric
> string, but atoi('+') does not generate an exception.
>
> Anything I can do about it? I managed to solve the problem with regexp
> matching:
>
> >>>
> myfloat=re.compile('^[+-]{0,1}\d+\.\d*$|^[+-]{0,1}\d*\.\d*[Ee][+-]*\d+$|^[+-]{0,1}\.\d+$')
>
> Is there a more elegant solution? (regexpwise or otherwise, I admit I'm
> not a very sophisticated user of regexps, AAMOF, I'm PERL illiterate).
Pretty much anything other than regexps would be more elegant. ;-)
I would use int() (and/or float(), if appropriate) and trap the
exceptions, much as you were using string.atoi().
Hm. Actually, now that I test it, string.atoi() does seem to
correctly throw exceptions on '+' and '-' in my setup. (1.5.2)
This appears to have changed sometime between 1.4 and 1.5.2.
-Justin
More information about the Python-list
mailing list