newbie str to int
Gerhard Häring
gh_pythonlist at gmx.de
Mon Oct 1 23:39:05 EDT 2001
On Tue, Oct 02, 2001 at 12:22:29PM +0800, James wrote:
> I am switching from Perl to Python, and would
> like to convert string '123abc' to integer 123.
123abc is no valid decimal number.
> foo = int('123abc') # error
> foo = string.atoi('123abc') #error
> foo = eval('123abc') # error
I'd expect this from a programming language.
> 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 ?
Because it's quite an artificial example? I've never needed anything
like this. Ignoring errors in input is not a good thing IMHO. In an
application, I'd alert the user that what he typed in is not a number
and that he, please, provide a valid number.
> Perl
> $foo = '123abc' + 0;
Why doesn't Perl convert this to 1194684? Isn't it smart enough to see
that 123abc is a hex number? ;-)
In one sentence: Python doesn't guess. And that's good.
Gerhard
--
mail: gerhard <at> bigfoot <dot> de registered Linux user #64239
web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))
More information about the Python-list
mailing list