I have a string variable which is a point, such as m="(2, 5)" or m="(-6, 7)". I want to extract the x coordinate and y coordinate and store them in different variables. Could someone provide some code in Python for how I could do this? Thanks!
            Asked
            
        
        
            Active
            
        
            Viewed 694 times
        
    -2
            
            
        - 
                    you can find the answer for your question here : [how-to-get-x-y-coordinates-using-python](https://stackoverflow.com/questions/36372068/how-to-get-x-y-coordinates-using-python) – Mohammed Chaaraoui Nov 13 '22 at 01:34
- 
                    I looked at that post but I don't see where my question is answered. Could u show where exactly the code is that would answer my question? Thanks! – PyTorchLearner Nov 13 '22 at 01:44
4 Answers
0
            
            
        maybe that help you
m = "(7, 5)"
x, y = m.strip('()').split(',')
print(x) # 7
print(y) # 5
with variables :
m = "(7, 5)"
x, y = m.strip('()').split(',')
var1 = x
var2 = y
print(var1)
print(var2)
 
    
    
        Mohammed Chaaraoui
        
- 279
- 2
- 11
0
            
            
        You can use the ast library. As explained in this answer for example https://stackoverflow.com/a/1894296/7509907
In your case you could do something like this:
import ast
m="(-2, 5.5)"
x, y = ast.literal_eval(m)
print(x, type(x))
print(y, type(y))
Output:
-2 <class 'int'>
5.5 <class 'float'>
This will also convert your values to integers/floats when needed.
 
    
    
        D.Manasreh
        
- 900
- 1
- 5
- 9
0
            
            
        Isolate the numbers from string.
m = "(2, 5)"
x, y = m.strip('()').split(',')
x, y
('2', ' 5')
Convert string numbers to float to allow them to be used mathematically. Can't do math with strings.
x, y = float(x), float(y)
x, y
(2.0, 5.0)
 
    
    
        Python16367225
        
- 121
- 6
-2
            
            
        Weird, but ok.
def coords(m):
  for i in range(2, len(m) - 2):
    if m[i] == ',':
      return m[1:i],m[(i+1),(len(m)-1)]
 
    
    
        lckcorsi
        
- 42
- 5
- 
                    
- 
                    Yeah, my python is rusty. I assume it's in the for loop range. Instead try: for i in range(2, len(m) - 2): – lckcorsi Nov 13 '22 at 01:49
- 
                    Yeah, I did a quick python syntax review and what I edited it to should be more accurate. – lckcorsi Nov 13 '22 at 01:53
