473,414 Members | 2,019 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,414 software developers and data experts.

convert a string to tuple

how do I convert
b is a string b = '(1,2,3,4)' to b = (1,2,3,4)

Jul 19 '05 #1
7 46209
In <11**********************@g43g2000cwa.googlegroups .com>, querypk wrote:
how do I convert
b is a string b = '(1,2,3,4)' to b = (1,2,3,4)


In [1]: b = '(1,2,3,4)'

In [2]: b[1:-1]
Out[2]: '1,2,3,4'

In [3]: b[1:-1].split(',')
Out[3]: ['1', '2', '3', '4']

In [4]: tuple(b[1:-1].split(','))
Out[4]: ('1', '2', '3', '4')

Ooops, you wanted ints in there:

In [5]: tuple(map(int, b[1:-1].split(',')))
Out[5]: (1, 2, 3, 4)

Ciao,
Marc 'BlackJack' Rintsch
Jul 19 '05 #2
Pass it to eval:
eval('(1, 2, 3, 4, 5)')

(1, 2, 3, 4, 5)

Basically what you are doing it evaluating the repr of the tuple.

-Brett

Jul 19 '05 #3
qu*****@gmail.com wrote:
b is a string b = '(1,2,3,4)' to b = (1,2,3,4)


py> tuple(int(s) for s in '(1,2,3,4)'[1:-1].split(','))
(1, 2, 3, 4)

Or if you're feeling daring:

py> eval('(1,2,3,4)', dict(__builtins__=None))
(1, 2, 3, 4)

Python makes no guarantees about the security of this second one though.

STeVe
Jul 19 '05 #4
bc*****@gmail.com wrote:
Pass it to eval:
eval('(1, 2, 3, 4, 5)')

(1, 2, 3, 4, 5)


Just be sure you know where your strings come from. You wouldn't want
someone to pass you
"""__import__('os').system('rm -rf /')"""
and then send that to eval. =)

STeVe
Jul 19 '05 #5
Steven Bethard wrote:
Just be sure you know where your strings come from. You wouldn't want
someone to pass you
"""__import__('os').system('rm -rf /')"""
and then send that to eval. =)


Why not, Steven? I just tried it and my compu
Jul 19 '05 #6
lol

Jul 19 '05 #7
On Tue, 31 May 2005 13:14:09 -0700, querypk wrote:
how do I convert
b is a string b = '(1,2,3,4)' to b = (1,2,3,4)


You can do:

def str2tuple(s):
"""Convert tuple-like strings to real tuples.
eg '(1,2,3,4)' -> (1, 2, 3, 4)
"""
if s[0] + s[-1] != "()":
raise ValueError("Badly formatted string (missing brackets).")
items = s[1:-1] # removes the leading and trailing brackets
items = items.split(',')
L = [int(x.strip()) for x in items] # clean up spaces, convert to ints
return tuple(L)

For real production code, you will probably want better error checking.

--
Steven.
Jul 19 '05 #8

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

Similar topics

3
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....
1
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...
1
by: Jinming Xu | last post by:
Hello everyone, While embedding my C++ program with Python, I am impeded by the conversion from a Python Tuple to a C++ array. I hope to get some assistance from you guys. I have a sequence...
16
by: flyaflya | last post by:
a = "(1,2,3)" I want convert a to tuple:(1,2,3),but tuple(a) return ('(', '1', ',', '2', ',', '3', ')') not (1,2,3)
1
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...
3
by: Amy L. | last post by:
I have a class that contains a string array. However, I can't get this object to serialize in the xml output. Is there a trick to get a string to serialize? Thanks Amy.
2
by: aqmaiya | last post by:
Hello, there is string value 'Dec 06, 2000' I want to convert that string date to SHORT FORMAT like '2000-12-06-. Please help me how do I do that? I'm new in Jython. Thanks, aqmaiya
8
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,...
0
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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,...
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...
0
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...

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.