Numeric Conversion

Iddo Friedberg idoerg at cc.huji.ac.il
Thu Dec 9 03:28:19 EST 1999


Hi all,

A small one: atoi &c. recognize the tokens '+' and '-' by themselves as
a numeric value; i.e.

>>> m=string.atoi('+')
>>> print m
0

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).

Thanks in advance,

Iddo Friedberg

--

.. -.. -.. ---   ..-. .-. .. . -.. -... .. .-. --.






More information about the Python-list mailing list