Search code examples
pythontuplessequencesplititerable-unpacking

Extracting integers from a string of ordered pairs in Python?


This may be super simple to a lot of you, but I can't seem to find much on it. I have an idea for it, but I feel like I'm doing way more than I should. I'm trying to read data from file in the format (x1, x2) (y1, y2). My goal is to code a distance calculation using the values x1, x2, y1 and y2.

Question: How do I extract the integers from this string?


Solution

  • with regex

    >>> import re
    >>> s = "(5, 42) (20, -32)"
    >>> x1, y1, x2, y2 = map(int, re.match(r"\((.*), (.*)\) \((.*), (.*)\)", s).groups())
    >>> x1, y1
    (5, 42)
    >>> x2, y2
    (20, -32)
    

    or without regex

    >>> x1, y1, x2, y2 = (int(x.strip("(),")) for x in s.split())