# newbie str to int

Michael Chermside mcherm at destiny.com
Tue Oct 2 23:33:02 CEST 2001

```> I am switching from Perl to Python, and would
> like to convert string '123abc' to integer 123.
>
> foo = int('123abc') # error
> foo = string.atoi('123abc') #error
> foo = eval('123abc') # error
>
> I tried the above, then tried the following.
>
> tmp = ''
> for i in '123abc':
>     if 47 < ord(i) < 58:
>         tmp += i
> foo = int(tmp) # yay
>
> Why doing simple thing like this is so complicated ?
>
> Perl
> \$foo = '123abc' + 0;
>

Well, what you need to do is to define the problem a little better.

If your problem is "Turn these ascii digits into a number", then
raising an exception is the RIGHT thing to do.

If your problem is "I have a string of 3 digits followed by 3 letters.
Turn it into a number.' then this works nicely:
>>> st = '123abc'
>>> foo = int(st[:3])

If your problem is "I have a string of mixed digits and letters. I want
to ignore all non-digits and construct a decimal integer from the
remaining digits.", as your code snippet suggests, then this is probably
an easier way to do it:

>>> import string
>>> st = '123abc'
>>> digit_list  = [x for x in st if x in string.digits]
>>> digit_string = ''.join(digit_list)
>>> foo = int(digit_string)

Is that more readable? At least it makes it very clear that you want to
discard non-digits in the incomming string.

Finally, your REAL problem statement MIGHT be this one:
"I have a string, which contains a number but maybe other junk, I
don't really know what. I want it to be turned into a number in
the 'right' way."

don't dispair: MOST of programming is like this. Put down the keyboard
and go do more analysis. Once you can specify the problem statement in a
form that doesn't require mind reading, you'll be ready to begin coding.
In my opinion, a language that attempts to do the mind reading for you
to save you the analysis step is a BAD idea, because analysis is almost
ALWAYS best done by humans. But if that's what you really want, there
are languages out there that will attempt it for you. Python is not one
of them.

-- Michael Chermside

```