newbie str to int

Andrei Kulakov sill at optonline.net
Wed Oct 3 19:11:00 EDT 2001


On Tue, 2 Oct 2001 12:22:29 +0800, James <no at email.com> wrote:
> 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 ?

It's not *that* complicated. First of all, if you have a bunch of numbers
and a bunch of letters and you want them separate, usually they're
separated by something, like a space. If they are, you can easily split
them and convert.. In your case they aren't separated, which is *very
unusual*. There's no reason why Python should guess answers for such rare
tasks.

However, you can do it much simpler/clearer, than what you do:

import string
lst = ""
for char in "123abc":
    if char in string.digits:
        lst += char
    else:
        break
num = int(lst)
> 
> Perl
> $foo = '123abc' + 0;

Why would I remember a separate rule that I may never use, ever? What if
you have $foo = $bar + 5, where you think $bar is a number whereas in fact
it is a string - python will tell you you're wrong, while perl will
happily add them up, causing potential subtle bugs later on. It's a
tradeoff, and I think perl chooses the wrong one. OTOH, keep in mind that
perl was intended for quick short cgi's and admin scripts, where this
isn't as big a problem, while python was meant to be more universal from
day one (i.e. subtle bugs of this sort are far more dangerous in a very
large multi-layered program).

> 
> Please explain in newsgroup.
> Many thanks in advance.

You are very welcome! Don't be scared off by perl-bashing :-).

> 
> 
> 


-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



More information about the Python-list mailing list