scanf string in python
andy at wild-flower.co.uk
Fri Jul 18 14:46:17 CEST 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)
> > y = int(tmplist)
> > z = int(tmplist)
> > But there should be a more convenient solution.
> some have suggested map, exec and re's. I came up with this list
> >>> mystring = '(1,2,3)'
> >>> mynumbers = [int(i) for i in mystring[1:-1].split(',')]
> >>> mynumbers
> [1, 2, 3]
> Jorgen Cederberg
(1, 2, 3)
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.
More information about the Python-list