0

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?

Stephen Paul
  • 2,762
  • 2
  • 21
  • 25
  • I don't really understand what you're asking. Could you give an example of the input data and the output you're looking for? – David Robinson Jul 02 '13 at 01:38
  • David: I'm trying to code a distance formula where I read a string from file, namely "(5, 42) (20, -32)", and I have to output the result. I'm just stomped on how to break that string of ordered pairs into a list of integers. – Stephen Paul Jul 02 '13 at 01:50

3 Answers3

3

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
>>>
rtrwalker
  • 1,021
  • 6
  • 13
  • RT: Thanks, but I forgot to mention that I'm reading in from file, so that ordered pair is read first as a string. I'm trying to break the string into integers that I can assign to vars. – Stephen Paul Jul 02 '13 at 01:58
  • @Stephen Paul, answer of gnibbler should do what you want – rtrwalker Jul 02 '13 at 02:12
3

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())
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

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
John
  • 13,197
  • 7
  • 51
  • 101