convert a string to tuple

B

bcannon

Pass it to eval:
(1, 2, 3, 4, 5)

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

-Brett
 
S

Steven Bethard

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
 
M

Marc 'BlackJack' Rintsch

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
 
S

Steven Bethard

Pass it to eval:

(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
 
P

Peter Hansen

Steven said:
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
 
S

Steven D'Aprano

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top