newbie str to int
Andy Todd
andy47 at halfcooked.com
Tue Oct 2 01:54:27 EDT 2001
"James" <no at email.com> wrote in <9pbetr$jp83 at imsp212.netvigator.com>:
>I am switching from Perl to Python, and would
>like to convert string '123abc' to integer 123.
>
If your string is always of that form (ie a three digit integer followed by
some non-numeric characters) then you just need;
>>> foo=int('123abc'[:3])
>>> foo
123
>>> print foo*2
246
>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
Yuck, too much Perl, must shut down brain.
Read the tutorial, in particular the section on string subscripting (in
section 3.1.2)
>
>Why doing simple thing like this is so complicated ?
Its not complicated. The important thing to bear in mind here is the format
of the data you wish to play about with. Where are you getting this string
from? Is it really one string or is it a number followed by a sequence of
characters? I find it much easier to store information in the smallest
possible chunks to avoid these kind of problems, you can construct much
more easily than you can slice and dice.
>
>Perl
>$foo = '123abc' + 0;
>
>Please explain in newsgroup.
>Many thanks in advance.
>
>
>
HTH,
Andy
--
Content free posts a speciality
More information about the Python-list
mailing list