Question

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?

Was it helpful?

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

OTHER TIPS

It's called sequence unpacking and can be done like this

>>> a =(1,2)
>>> x1,x2=a
>>> x1
1
>>> x2
2
>>> b = [[1,2],[2,3]]
>>> (x1,x2),(y1,y2)=b
>>> x1
1
>>> x2
2
>>> y1
2
>>> y2
3
>>>

If you are trying to get the values out of some lists and into variables this is one way to do it.

>>> x1, y1, x2, y2 = [1, 2] + [3, 4]
>>> x1
1
>>> x2
3
>>> y1
2
>>> y2
4
>>> 

tuples will exhibit the same behavior.

x1, y1, x2, y2 = (1, 2) + (3, 4)

Here is how to read the input out of a file and parse it using gnibbler's regular expression

import re

with open("myfile.txt", 'r') as file_handle:

    for line in file_handle:
        x1, y1, x2, y2 = map(int, re.match(r"\((.*), (.*)\) \((.*), (.*)\)", line).groups())
        print x1, y1, x2, y2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top