Q:

Splitting a string of tuples into tuples

I have a string of tuples where each tuple is separated by a comma. How do I split it into a list of tuples?
For example, I'd want to split this string:
"(2,3) (3, 4) ( 5, 4)"

Into this array of tuples:
[(2,3) , (3,4),(5,4)]

Note that there may be spaces within tuple (like "(3, 4)") so str.split() then using eval() will not work.

A:

You can use re.split with ast.literal_eval:
import re, ast
result = [ast.literal_eval(i) for i in re.split('(?<=\))\s(?=\()', "(2,3) (3, 4) ( 5, 4)")]

Output:
[(2, 3), (3, 4), (5, 4)]

Note that ast.literal_eval is much more secure that the builtin eval, as ast.literal_eval does not blindly evaluate whatever is passed to it, and instead checks if the input is a valid Python datatype.
However, the above will not work if the tuples in string form are not separated by a space i.e "(2,3)(3, 4)(5, 6)". In that case, you can create a small parser:
class Parse:
  def __init__(self, _input, _start=''):
    self.data, self.group, self.content = _input, _start, []
    self.parse()
  def __iter__(self):
    yield from map(ast.literal_eval, self.content)
  def parse(self):
    _val = next(self.data, None)
    if _val is not None:
       if _val == '(':
         r = Parse(self.data, _start="(")
         self.content.extend(r.content)
         self.data = r.data
       elif _val == ')':
         self.content.append(self.group+')')
       else:
         self.group += _val
       self.parse()

final_result = list(Parse(iter("(2,3)(3, 4)(5, 6)")))

Output:
[(2, 3), (3, 4), (5, 6)]

