469,949 Members | 2,723 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,949 developers. It's quick & easy.

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 45865
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 discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Lukas Kasprowicz | last post: by
1 post views Thread by Michal Mikolajczyk | last post: by
1 post views Thread by Jinming Xu | last post: by
16 posts views Thread by flyaflya | last post: by
1 post views Thread by Bell, Kevin | last post: by
2 posts views Thread by aqmaiya | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.