473,770 Members | 2,147 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 23016
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
18202
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
10869
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
5577
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
46236
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
3112
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
20017
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
1801
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
25792
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
9619
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
9454
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10102
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
10038
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
8933
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7460
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5354
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
4007
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
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.