473,405 Members | 2,354 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

string to list of numbers conversion

Hi,
I have a string '((1,2), (3,4))' and I want to convert this into a
python tuple of numbers. But I do not want to use eval() because I do
not want to execute any code in that string and limit it to list of
numbers.
Is there any alternative way?

Thanks.
Suresh

Nov 5 '06 #1
9 2121

jm*******@no.spam.gmail.com wrote:
Hi,
I have a string '((1,2), (3,4))' and I want to convert this into a
python tuple of numbers. But I do not want to use eval() because I do
not want to execute any code in that string and limit it to list of
numbers.
Is there any alternative way?

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>s = '((1,2), (3,4))'
s = filter(lambda char: char not in ')(', s)
s
'1,2, 3,4'
>>s = s.split(',')
s
['1', '2', ' 3', '4']
>>s = map(float, s)
s
[1.0, 2.0, 3.0, 4.0]
>>t1 = s[::2]
t1
[1.0, 3.0]
>>t2 = s[1::2]
t2
[2.0, 4.0]
>>zip(t1, t2)
[(1.0, 2.0), (3.0, 4.0)]
>>>
Gerard

Nov 5 '06 #2
jm*******@no.spam.gmail.com wrote:
I have a string '((1,2), (3,4))' and I want to convert this into a
python tuple of numbers. But I do not want to use eval() because I do
not want to execute any code in that string and limit it to list of
numbers.
Is there any alternative way?
http://aspn.activestate.com/ASPN/Coo.../Recipe/364469

Peter
Nov 5 '06 #3
Peter, Thanks.

This recipe fails when negative numbers are used.

safe_eval('(12, -12)')
*** Unsafe_Source_Error: Line 1. Unsupported source construct:
compiler.ast.UnarySub

But, I think it could be easily fixed for somebody who understands the
script. Can somebody help.

Thanks.
Suresh
Peter Otten wrote:
jm*******@no.spam.gmail.com wrote:
I have a string '((1,2), (3,4))' and I want to convert this into a
python tuple of numbers. But I do not want to use eval() because I do
not want to execute any code in that string and limit it to list of
numbers.
Is there any alternative way?

http://aspn.activestate.com/ASPN/Coo.../Recipe/364469

Peter
Nov 5 '06 #4

jm*******@no.spam.gmail.com wrote:
Hi,
I have a string '((1,2), (3,4))' and I want to convert this into a
python tuple of numbers. But I do not want to use eval() because I do
not want to execute any code in that string and limit it to list of
numbers.
Is there any alternative way?
This is a possibile solution, no input errors are taken into account:
>>s = '((1,2), (3,4), (-5,9.2))'
from string import maketrans
tab = maketrans("(), ", " "*4)
s.translate(tab)
' 1 2 3 4 -5 9.2 '
>>l = s.translate(tab).split()
l
['1', '2', '3', '4', '-5', '9.2']
>>l2 = map(float, l)
l2
[1.0, 2.0, 3.0, 4.0, -5.0, 9.1999999999999993]
>># This is partition(l2, 2)
[l2[i:i+2] for i in xrange(0, len(l2), 2)]
[[1.0, 2.0], [3.0, 4.0], [-5.0, 9.1999999999999993]]

Bye,
bearophile

Nov 5 '06 #5
jm*******@no.spam.gmail.com wrote:
This recipe fails when negative numbers are used.

safe_eval('(12, -12)')
*** Unsafe_Source_Error: Line 1. Unsupported source construct:
compiler.ast.UnarySub

But, I think it could be easily fixed for somebody who understands the
script.
I think that somebody could be you.
Can somebody help.
Start with

class SafeEval(object):
# ...
def visitUnarySub(self, node, **kw):
return -node.expr.value

and then add some error handling.

Peter

Nov 5 '06 #6
jm*******@no.spam.gmail.com wrote:
Hi,
I have a string '((1,2), (3,4))' and I want to convert this into a
python tuple of numbers. But I do not want to use eval() because I do
not want to execute any code in that string and limit it to list of
numbers.
Is there any alternative way?

Thanks.
Suresh

s = '((1,2), (3,4))'
separators = re.compile ('\(\s*\(|\)\s*,\s*\(|\)\s*\)')
tuple ([(float (n[0]), float (n[1])) for n in [pair.split (',') for pair
in separators.split (s) if pair]])
((1.0, 2.0), (3.0, 4.0))

Frederic
Nov 6 '06 #7
"jm*******@no.spam.gmail.com" <jm*******@gmail.comwrote in message
news:11**********************@i42g2000cwa.googlegr oups.com...
Hi,
I have a string '((1,2), (3,4))' and I want to convert this into a
python tuple of numbers. But I do not want to use eval() because I do
not want to execute any code in that string and limit it to list of
numbers.
Is there any alternative way?

Thanks.
Suresh
Pyparsing comes with an example that parses strings representing lists.
Here's that example, converted to parsing only tuples of numbers. Note that
this does not presume that tuples are only pairs, but can be any number of
numeric values, nested to any depth, and with arbitrary whitespace, etc.
This grammar also includes converters by type, so that ints come out as
ints, and floats as floats. (This grammar doesn't handle empty tuples, but
it does handle tuples that include an extra ',' after the last tuple
element.)

-- Paul
Download pyparsing at http://sourceforge.net/projects/pyparsing/ .
from pyparsing import *

integer = (Word(nums)|Word('-+',nums)).setName("integer")
real = Combine(integer + "." + Optional(Word(nums))).setName("real")
tupleStr = Forward().setName("tuple")
tupleItem = real | integer | tupleStr
tupleStr << ( Suppress("(") + delimitedList(tupleItem) +
Optional(Suppress(",")) + Suppress(")") )

# add parse actions to do conversion during parsing
integer.setParseAction( lambda toks: int(toks[0]) )
real.setParseAction( lambda toks: float(toks[0]) )
tupleStr.setParseAction( lambda toks: tuple(toks) )

s = '((1,2), (3,4), (-5,9.2),)'
print tupleStr.parseString(s)[0]

Gives:
((1, 2), (3, 4), (-5, 9.1999999999999993))
Nov 6 '06 #8
jm*******@no.spam.gmail.com wrote:
I have a string '((1,2), (3,4))' and I want to convert this into a
python tuple of numbers. But I do not want to use eval() because I do
not want to execute any code in that string and limit it to list of
numbers.
here's yet another approach:

http://online.effbot.org/2005_11_01_...imple-parser-1

also see:

http://online.effbot.org/2005_11_01_...imple-parser-3

</F>

Nov 6 '06 #9
jm*******@no.spam.gmail.com skrev:
Hi,
I have a string '((1,2), (3,4))' and I want to convert this into a
python tuple of numbers.
I think your question is deeper and more natural than is clear from the
many recepies given so far in this thread, so I'll take on another
point of view,
>From a language design perspective, there is no reason why not the
parsing capacity of the Python interpreter would be accessible in a
modular fashion to the user/programmer. E.g used like this:

I an imaginable Python, define you expect for an answer. In this case:
(1)
# import junctions, types from maybefuture:-)
string = ((1,2), (3,4))
type a = tuple a | int
myTuple = eval(string, goal=a)
Obviously, if you expect _only_ the given form, then this might be
better:

(2)
# import types from maybefuture:-)
type a = ((int,int),(int,int))
myTuple = eval(string, goal=a)

Note the use of a "a|b" in line 2 (I think Perl 6 is among the few
programming languages giving a reasonable semantics to junctions so
far).

Version 2 above sholud not be a big addition to Python conceptually.
Motivation:
It is easy to think clearly about.
It makes it easier to use eval safely and makes code more readable.

This is a topic of interest to me, so feel free to post either on list
or directly to me.

Thanks/Henning

Nov 9 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: ken | last post by:
I've been looking for a solution to a string to long conversion problem that I've run into >>> x = 'e10ea210' >>> print x e10ea210 >>> y=long(x) Traceback (most recent call last): File...
7
by: Kamilche | last post by:
I want to convert a dict into string form, then back again. After discovering that eval is insecure, I wrote some code to roll a Python object, dict, tuple, or list into a string. I've posted it...
5
by: Tony Vasquez | last post by:
I want to turn the string "100,144" to numbers, to use for resizeTo(100,144) <--- here. Please advice, or post scriptlette. Thanks Tony Vasquez
8
by: Kenny | last post by:
I've run into this problem a couple of times. When I try to get a value from a form text field and add them together like so… a = document.myform.field1.value b = document.myform.field2.value c...
4
by: costantinos | last post by:
Hello. I have a string which looks like and I need to read these numbers. The logical implementation was to read the string char by char and check whether I have a space and when I find one I...
3
by: d.avitabile | last post by:
I have a C++ code that is reading a list of parameters from a file. PARAMETERS stringParam="stringValue", intParam=4, doubleParam = 3.533, ... END The values can be strings as well as integers...
2
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number?...
11
by: davidj411 | last post by:
i am parsing a cell phone bill to get a list of all numbers and the total talktime spend on each number. i already have a unique list of the phone numbers. now i must go through the list of...
0
by: Lie Ryan | last post by:
On Wed, 01 Oct 2008 09:41:57 -0700, sandric ionut wrote: Here you defined nameAll as a list That range is superfluous, you could write this instead: for i in range(10): in this, you're...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.