scanf string in python

Andy Jewell andy at wild-flower.co.uk
Fri Jul 18 08:46:17 EDT 2003


On Friday 18 Jul 2003 8:39 am, Jørgen Cederberg wrote:
> lehrig wrote:
> > lehrig wrote:
> >>I have a string which is returned by a C extension.
> >>
> >>mystring = '(1,2,3)'
> >>
> >>HOW can I read the numbers in python ?
> >
> > Now I have done it like this:
> >   tmp = mystring[1:-1]
> >   tmplist = string.split(tmp,',')
> >   x = int(tmplist[0])
> >   y = int(tmplist[1])
> >   z = int(tmplist[2])
> >
> > But there should be a more convenient solution.
>
> Hi,
>
> some have suggested map, exec and re's. I came up with this list
> comprehenion
>
>  >>> mystring = '(1,2,3)'
>  >>> mynumbers = [int(i) for i in mystring[1:-1].split(',')]
>  >>> mynumbers
>
> [1, 2, 3]
>
> regards
> Jorgen Cederberg

what about:

x,y,z=eval(mystring)

???
see:

>>> x,y,z=eval(mystring)
>>> x,y,z
(1, 2, 3)
>>> x
1
>>> y
2
>>> z

NOTE: this could introduce exploitable behaviour if you can't guarantee that 
the string is *only* going to contain a tuple of nembers... think about what 
could happen if the  c code returned 'ReallyNastyFunc()' instead of 
"(1,2,3)"... :-(.  As long as you can guarantee the value won't be 
'dangerous' you'll be ok.

hth -ndyj







More information about the Python-list mailing list