Home > Software engineering >  How to get the x and y coordinate from an (x,y) point in Python?
How to get the x and y coordinate from an (x,y) point in Python?

Time:11-13

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!

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

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)]
  • Related