Numeric Conversion

Remco Gerlich scarblac-spamtrap at pino.selwerd.cx
Thu Dec 9 05:37:34 EST 1999


Iddo Friedberg <idoerg at cc.huji.ac.il> wrote:
> 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.

>>> import string
>>> m=string.atoi('+')
Traceback (innermost last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for atoi(): '+'

So I can't reproduce your problem. Are you sure?

And even if you have such a problem, what's wrong with doing something like

if s == '+': raise(ValueError("Invalid literal for atoi: '+'"))

yourself, before the atoi call?

-- 
Remco Gerlich,  scarblac at pino.selwerd.cx
"This gubblick contains many nonsklarkish English flutzpahs, but the
 overall pluggandisp can be glorked from context"  (David Moser)



More information about the Python-list mailing list