Extract tuples from space separated string of tuples.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sudeepto
    New Member
    • Jun 2015
    • 2

    Extract tuples from space separated string of tuples.

    I have string in the following form:

    Code:
     my_string = '(1, 2) (3, 4)'
    As you can see, the tuples inside the string are space separated. I want to know how can I extract those tuples into separate variables.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    There may be a better way.
    Code:
    >>> my_string = '(1, 2) (3, 4)'
    >>> eval(my_string.replace(") (", "),("))
    ((1, 2), (3, 4))
    >>> a,b = eval(my_string.replace(") (", "),("))
    >>> a
    (1, 2)
    >>> b
    (3, 4)
    >>>

    Comment

    • sudeepto
      New Member
      • Jun 2015
      • 2

      #3
      Thank you bvdet. But I have a question.

      Can you please explain me what is happening in the code ?? I have never used eval function in Python.

      Also I have read that using eval is not recommended in Python. Can you tell me why is that ??

      EDIT: I used your approach of substituting the
      Code:
      ) (
      part with
      Code:
      ), (
      so that I get the string

      Code:
      (1, 2), (3, 4)
      Then after that, I searched on StackOverflow about ast module and literal_eval function.

      converting-string-to-tuple

      I used it to separate the tuples into variables.

      Thank You for the help .

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Built-in funcation eval: Python documentation for eval

        The function could potentially evaluate malicious code, therefore its use if sometimes frowned upon. A regex solution could potentially be a more robust but complicated solution.

        Code:
        >>> import re
        >>> re.compile("[(](\d+, \d+)[)]")
        <_sre.SRE_Pattern object at 0x0000000005C3EA80>
        >>> pattern = re.compile("[(](\d+, \d+)[)]")
        >>> pattern.findall('(1, 2) (3, 4)')
        ['1, 2', '3, 4']
        >>> ((int(i) for i in item.split(",")) for item in pattern.findall('(1, 2) (3, 4)'))
        <generator object <genexpr> at 0x0000000005E7CD38>
        >>> for obj in ((int(i) for i in item.split(",")) for item in pattern.findall('(1, 2) (3, 4)')):
        ... 	print tuple(obj)
        ... 	
        (1, 2)
        (3, 4)
        >>>

        Comment

        Working...