473,696 Members | 1,675 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to convert string to list or tuple

a = "(1,2,3)"
I want convert a to tuple:(1,2,3),b ut tuple(a) return ('(', '1', ',',
'2', ',', '3', ')') not (1,2,3)
Jul 19 '05 #1
16 23009
On 5/26/05, flyaflya <fl******@gmail .com> wrote:
a = "(1,2,3)"
I want convert a to tuple:(1,2,3),b ut tuple(a) return ('(', '1', ',',
'2', ',', '3', ')') not (1,2,3)


Short answer - use eval().

Long answer - *don't* use eval unless you are in control of the source
of the string that you are evaluating.

--
Cheers,
Simon B,
si***@brunningo nline.net,
http://www.brunningonline.net/simon/blog/
Jul 19 '05 #2
"flyaflya" <fl******@gmail .com> wrote:
a = "(1,2,3)"
I want convert a to tuple:(1,2,3),b ut tuple(a) return ('(', '1', ',',
'2', ',', '3', ')') not (1,2,3)


if you trust the source, use

eval(a)

if you don't trust it, you can use, say

tuple(int(x) for x in re.findall("\d+ ", a))

or, perhaps

tuple(int(x) for x in a[1:-1].split(","))

or some variation thereof.

(if you're using a version older than 2.4, add brackets inside
the tuple() call:

tuple([int(x) for x in a[1:-1].split(",")])

etc.

</F>

Jul 19 '05 #3
On Thu, 26 May 2005 19:53:38 +0800, flyaflya wrote:
a = "(1,2,3)"
I want convert a to tuple:(1,2,3),b ut tuple(a) return ('(', '1', ',',
'2', ',', '3', ')') not (1,2,3)


Others have already given some suggestions. Here are some others.

You didn't say where the input string a came from. Do you control
it? Instead of using:

String_Tuple_To _Real_Tuple("(1 ,2,3)")

can you just create the tuple in the first place?

a = (1, 2, 3)

Second suggestion: if you know that the input string will ALWAYS be in the
form "(1,2,3)" then you can do this:

a = "(1,2,3)"
a = a[1:-1] # deletes leading and trailing parentheses
a = a.split(",") # creates a list ["1", "2", "3"] (items are strings)
a = [int(x) for x in a] # creates a list [1, 2, 3] (items are integers)
a = tuple(a) # coverts to a tuple

or as a one-liner:

a = "(1,2,3)"
a = tuple([int(x) for x in a[1:-1].split(",")])

Best of all, wrap your logic in a function definition with some
error-checking:

def String_Tuple_To _Real_Tuple(s):
"""Return a tuple of ints from a string that looks like a tuple."""
if not s:
return ()
if (s[0] == "(") and s[-1] == ")"):
s = s[1:-1]
else:
raise ValueError("Mis sing bracket(s) in string.")
return tuple([int(x) for x in s.split(",")])
Hope this helps,
--
Steven.
Jul 19 '05 #4
Simon Brunning wrote:
On 5/26/05, flyaflya <fl******@gmail .com> wrote:
a = "(1,2,3)"
I want convert a to tuple:(1,2,3),b ut tuple(a) return ('(', '1', ',',
'2', ',', '3', ')') not (1,2,3)


Short answer - use eval().

Long answer - *don't* use eval unless you are in control of the source
of the string that you are evaluating.


Or if you do use eval, don't give it access to any names.
import os
eval(raw_input( ), {})

os.system("rm -rf *")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 0, in ?
NameError: name 'os' is not defined

Jul 19 '05 #5
Dan Bishop wrote:
Simon Brunning wrote:
[...]


Or if you do use eval, don't give it access to any names.
[...]

os.system("rm -rf *")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 0, in ?
NameError: name 'os' is not defined

Have you tried giving it the string '__import__("os ").system(" rm -rf *")'?
[Don't try that at home children!]

Even if you take steps to avoid that working by hiding the builtins, there
are still too many ways to do nasty things with eval for it ever to be
safe.

Jul 19 '05 #6

"Duncan Booth" <du**********@i nvalid.invalid> wrote in message
news:Xn******** *************** **@127.0.0.1...
Dan Bishop wrote:
Simon Brunning wrote:
[...]
Or if you do use eval, don't give it access to any names.
[...]

os.system("rm -rf *")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 0, in ?
NameError: name 'os' is not defined

Have you tried giving it the string '__import__("os ").system(" rm -rf *")'?
[Don't try that at home children!]

Even if you take steps to avoid that working by hiding the builtins, there
are still too many ways to do nasty things with eval for it ever to be
safe.


There was a posting here Nov 5, 2003 by Huaiyu Zhu at IBM Almaden
that shows how to do eval type stuff safely. The basic notion is to use the
compiler and then check the ast to see if the result fits the straitjacket
you
want to put it into. Pass / Fail; trying to fix it up if it's "close" is
usually a
real bad idea.

He gives an example, and there's a much more extensive set of working
code in the taBase.py module of PyFit that handles lists, tuples and
dicts which contain arbitrary literals including complex and arbitrarily
nested
lists, tuples and dicts.

------- code snippet starts here --------

def _safeEval(self, s):
"""
Evaluate strings that only contain the following structures:
const, tuple, list, dict
Taken from c.l.py newsgroup posting Nov 5, 2003 by Huaiyu Zhu at IBM
Almaden
"""
#print "in _safeEval. input: '%s'" % s
node1 = compiler.parse( s)

# !!! special case of attempting to compile a lone string
if node1.doc is not None and len(node1.node. nodes) == 0:
#print "in _safeEval. string: '%s' found as docstring" %
node1.doc
return node1.doc

#print "in _safeEval. nodes: '%s'" % (node1,)
stmts = node1.node.node s
assert len(stmts) == 1
node = compiler.parse( s).node.nodes[0]
assert node.__class__ == compiler.ast.Di scard
nodes = node.getChildNo des()
assert len(nodes) == 1
result = self._safeAssem ble(nodes[0])
#print "in _safeEval result: '%s'" % (result,)
return result

seq_types = {
compiler.ast.Tu ple: tuple,
compiler.ast.Li st: list,
}
map_types = {
compiler.ast.Di ct: dict,
}

oper_types = {
compiler.ast.Ad d: operator.add,
compiler.ast.Su b: operator.sub,
}

builtin_consts = {
"True": True,
"False": False,
"None": None,
}

def _safeAssemble(s elf, node):
""" Recursively assemble parsed ast node """
cls = node.__class__
if cls == compiler.ast.Co nst:
return node.value
elif cls in self.seq_types:
nodes = node.nodes
args = map(self._safeA ssemble, nodes)
return self.seq_types[cls](args)
elif cls in self.map_types:
keys, values = zip(*node.items )
keys = map(self._safeA ssemble, keys)
values = map(self._safeA ssemble, values)
return self.map_types[cls](zip(keys, values))
elif cls in self.oper_types :
left = self._safeAssem ble(node.left)
right = self._safeAssem ble(node.right)
if type(left) == type(1.0j) or type(right) == type(1.0j):
return self.oper_types[cls](left, right)
else:
raise FitException, ("Parse001", )
elif cls == compiler.ast.Na me:
result = self.builtin_co nsts.get(node.n ame, "?")
if result != "?":
return result
else:
raise FitException, ("Parse002", node.name)
else:
raise FitException, ("Parse003", cls)

------- end of code snippet -----------

John Roth



Jul 19 '05 #7
Duncan Booth wrote:
Dan Bishop wrote:
Or if you do use eval, don't give it access to any names. [snip] os.system("rm -rf *")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 0, in ?
NameError: name 'os' is not defined


Have you tried giving it the string '__import__("os ").system(" rm -rf *")'?
[Don't try that at home children!]


But you can try it at home if you set __builtins__ to something other
than the default:

py> eval("""__impor t__("os").syste m('echo "hello"')"" ",
dict(__builtins __=None))
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<string>", line 0, in ?
NameError: name '__import__' is not defined

If you're just doing work with constants, the lack of access to any
builtins is ok:

py> eval("(1,2,3)", dict(__builtins __=None))
(1, 2, 3)

I know there have been security holes in this technique before, but I
looked at the archives, and all the old ones I found have been patched.
(Or at least I wasn't able to reproduce them.)

STeVe
Jul 19 '05 #8
Steven Bethard wrote:
Have you tried giving it the string '__import__("os ").system(" rm -rf
*")'? [Don't try that at home children!]


But you can try it at home if you set __builtins__ to something other
than the default:

py> eval("""__impor t__("os").syste m('echo "hello"')"" ",
dict(__builtins __=None))
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<string>", line 0, in ?
NameError: name '__import__' is not defined

If you're just doing work with constants, the lack of access to any
builtins is ok:

py> eval("(1,2,3)", dict(__builtins __=None))
(1, 2, 3)

I know there have been security holes in this technique before, but I
looked at the archives, and all the old ones I found have been
patched.
(Or at least I wasn't able to reproduce them.)

I guess you are referring to things like this not working when you use eval
with an empty __builtins__:

eval('''[ cls for cls in {}.__class__.__ bases__[0].__subclasses__ ()
if '_Printer' in `cls`
][0]._Printer__setu p.func_globals['__builtins__']['__import__']''',
dict(__builtins __=None))

That gets blocked because func_globals is a 'restricted attribute', so I
can't get directly at __import__ that way, but what I can do is to access
any new style class you have defined and call any of its methods with
whatever arguments I wish.

Even with the big holes patched you are going to find it pretty hard to
write a safe program that uses eval on untrusted strings. The only way to
go is to filter the AST (or possibly the bytecode).
Jul 19 '05 #9
Duncan Booth wrote:
Steven Bethard wrote:
But you can try it at home if you set __builtins__ to something other
than the default:

py> eval("""__impor t__("os").syste m('echo "hello"')"" ",
dict(__builti ns__=None))
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<string>", line 0, in ?
NameError: name '__import__' is not defined
[snip]
I know there have been security holes in this technique before, but I
looked at the archives, and all the old ones I found have been
patched.
(Or at least I wasn't able to reproduce them.)
I guess you are referring to things like this not working when you use eval
with an empty __builtins__:

eval('''[ cls for cls in {}.__class__.__ bases__[0].__subclasses__ ()
if '_Printer' in `cls`
][0]._Printer__setu p.func_globals['__builtins__']['__import__']''',
dict(__builtins __=None))

That gets blocked because func_globals is a 'restricted attribute', so I
can't get directly at __import__ that way


Among other things, yes, that's one of the big ones. func_globals is
inaccessible. Also, IIRC the file constructor is inaccessible.
but what I can do is to access
any new style class you have defined and call any of its methods with
whatever arguments I wish.


Any new style class that I've defined? Or just any one I pass in as
part of dict(__builtins __=None, ...)? If the former, could you
elaborate? If the latter, then yes, I can see the problem. However for
the case where all you pass in is dict(__builtins __=None), is there
still a risk? Note that in the OP's case, all that is necessary is
constant parsing, so no names need to be available.

STeVe
Jul 19 '05 #10

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

Similar topics

3
18191
by: Lukas Kasprowicz | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Folks, My Proglem is, I get after a query on a mysql database with module MySQLdb a tuple but I need this output from database as a string. can anybody help? - -------------- database ---------
1
10864
by: Michal Mikolajczyk | last post by:
Is there a quick way to convert a unicode tuple to a tuple containing python strings? (u'USER', u'NODE', u'HASH', u'IDNBR') to this: ('USER', 'NODE', 'HASH', 'IDNBR') I need to be able to do this for a lot of tuples, not just one.
2
5571
by: bwooster47 | last post by:
I'm a newcomer to python - what is the best way to convert a list into a function call agruments? For example: list = (2005, 5, 5) date = datetime.date( list ) fails with: TypeError: function takes exactly 3 arguments (1 given)
7
46233
by: querypk | last post by:
how do I convert b is a string b = '(1,2,3,4)' to b = (1,2,3,4)
1
3105
by: Bell, Kevin | last post by:
I'm pulling a range of cells from Excel into a list and the data in Excel is a number or possibly some text like an asterisk. Each member of the list is a com object (I think) and I'm converting them to integers (or to None if not numberic) but my method seems very silly. Is this the best way to go about it? It does exactly what it should, but it seems like a lot of extra BS to convert my object to a string to a float to a rounded...
5
20011
by: Jon Bowlas | last post by:
Hi listers, I wrote this script in Zope some time ago and it worked for a while, but now I'm getting the following error: TypeError: coercing to Unicode: need string or buffer, NoneType found Here's my script: results = context.module_retriever().tuples() # call to ZSQLMethod converted =
2
1798
by: Tim Chase | last post by:
Is there an easy way to make string-formatting smart enough to gracefully handle iterators/generators? E.g. transform = lambda s: s.upper() pair = ('hello', 'world') print "%s, %s" % pair # works print "%s, %s" % map(transform, pair) # fails with a """ TypeError: not enough arguments for format string
8
25785
by: hidrkannan | last post by:
I am reading a set of data from the excel workbook. Data are contained in 2 columns. Column A contains the names and Column B contains values. The issue is the value can be of any type integer, float, string, list or a tuple. When I read the data from a Cell it is read as of data type unicode. I would like to convert the unicode data type to list type if the data I read is of list type and similarly for tuples. Please suggest if this...
0
218
by: dudeja.rajat | last post by:
On Tue, Aug 19, 2008 at 12:40 PM, <dudeja.rajat@gmail.comwrote: Googled and found : s = "v%d.%d.%d.%d" % tuple(version) print s it's working. Result is : v1.2.3.4
0
8661
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9142
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9008
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8875
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8849
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5855
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4353
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3030
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2313
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.