Conversion of string to integer

John Machin sjmachin at lexicon.net
Mon Jan 29 18:29:12 EST 2007



On Jan 30, 6:48 am, "witte... at hotmail.com" <martin.wi... at gmail.com> 
wrote:
> On Jan 29, 2:55 pm, "jupiter" <anil.jupit... at gmail.com> wrote:
>
>
>
> > Hi guys,
>
> > I have a problem. I have a list which contains strings and numeric.
> > What I want is to compare them in loop, ignore string and create
> > another list of numeric values.
>
> > I tried int() and decimal() but without success.
>
> > eq of problem is
>
> > #hs=string.split(hs)
> > hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"]
>
> > j=0
> >     for o in range(len(hs)):
> >         print hs[o],o
> >         p=Decimal(hs[o])
> >         if p > 200: j+=j
> >         print "-"*5,j
> >     print "*"*25
>
> > I could be the best way to solve this ......?
>
> > @nilfunction isinstance can help you to determine the type/class of an
> object:
>
> py>hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"]
> py>
> py>for i in hs:
> py>    if isinstance(i, str):
> py>        print str(i)
> py>    elif isinstance(i, float):
> py>        print float(i)
> py>    elif isinstance(i, int):
> py>        print int(i)
> py>    else:
> py>        print 'dunno type of this element: %s' % str(i)
> popopopopop
> 254.25
> pojdjdkjdhhjdccc
> 25452.25

Call me crazy, but I can't understand what the above code is meant to 
demonstrate.

(1) All of the elements in "hs" are *known* to be of type str. The 
above code never reaches the first elif. The OP's problem appears to 
be to distinguish which elements can be *converted* to a numeric type.

(2) if isinstance(i, some_type) is true, then (usually) some_type(i) 
does exactly nothing that is useful

Awaiting enlightenment ...

John




More information about the Python-list mailing list