Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a tuple from a string?

Say I have a string that's of the same form a tuple should be, for example, "(1,2,3,4,5)". What's the easiest way to convert that into an actual tuple? An example of what I want to do is:

tup_string = "(1,2,3,4,5)" tup = make_tuple(tup_string) 

Just running tuple() on the string make the whole thing one big tuple, whereas what I'd like to do is comprehend the string as a tuple. I know I can use a regex for this, but I was hoping there's a less costly way. Ideas?

like image 472
Eli Avatar asked Mar 18 '12 23:03

Eli


People also ask

How do you parse a string into a tuple?

When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.

How do you decode a tuple of a string in Python?

Create an empty string and using a for loop iterate through the elements of the tuple and keep on adding each element to the empty string. In this way, the tuple is converted to a string. It is one of the simplest and the easiest approaches to convert a tuple to a string in Python.

Which function is used to convert a string into tuple?

Python's built-in function tuple() converts any sequence object to tuple. If it is a string, each character is treated as a string and inserted in tuple separated by commas. Any non-sequence object as argument results in TypeError.


2 Answers

It already exists!

>>> from ast import literal_eval as make_tuple >>> make_tuple("(1,2,3,4,5)") (1, 2, 3, 4, 5) 

Be aware of the corner-case, though:

>>> make_tuple("(1)") 1 >>> make_tuple("(1,)") (1,) 

If your input format works different than Python here, you need to handle that case separately or use another method like tuple(int(x) for x in tup_string[1:-1].split(',')).

like image 141
Niklas B. Avatar answered Oct 05 '22 22:10

Niklas B.


I would recommend using literal_eval.

If you are not comfortable with literal_eval or want to have more control on what gets converted you can also disassemble the string, convert the values and recreate the tuple.

Sounds more complicated than it is, really, it's a one-liner:

eg = '(102,117,108)' eg_tuple = map(int, eg.replace('(','').replace(')','').split(','))) 

This would throw a ValueError if any element (string) in the tuple is not convertible to int, like, for example the '1.2' in the string: '(1.2, 3, 4)'.


The same can be achieved with regex:

import re eg = '(102,117,108)' et_tuple = tuple(map(int, re.findall(r'[0-9]+', eg))) 
like image 42
jojo Avatar answered Oct 05 '22 22:10

jojo