Python | Convert location coordinates to tuple

Python Methods and Functions

Method # 1: Using tuple () + float () + split () + map ()

A combination of the above functions can be used to complete this task. In this, we first split the two pieces of coordinates into a list, apply the float function to each one using float () and map () and finally it is converted to a tuple with using tuple () .

# Python3 code to demonstrate how it works
# Convert location coordinates to tuple
# Using tuple () + float () + split () + map ()

 
# Initializing string

test_str = "44.6463, -49.583"

  
# print the original line

print ( "The original string is:" + str (test_str))

 
# Convert location coordinates to tuple
# Using tuple () + float () + split () + map ()

res = tuple ( map ( float , test_str.split ( ',' )))

 
# print result

print ( "The coordinates after conversion to tuple are:" + str (res))

Output:

 The original string is: 44.6463, -49.583 The coordinates after conversion to tuple are: (44.6463, -49.583) 

Method # 2: Using eval()
This is a one-line and recommended method to accomplish this particular task. In this case, eval () internally detects the string and converts it to a floating point number, delimited as tuple elements.

# Python3 demo code
# Convert location coordinates to tuple
# Using eval ()

 
# Initializing string

test_str = "44.6463, -49.583"

 
# print original line

print ( "The original string is:" + str < code class = "plain"> (test_str))

 
# Convert coordinates locations in a tuple
# Using eval ()

res = eval (test_str)

 
# print result

print ( "The coordinates after conversion to tuple are:" + str (res))

Output:

 The original string is: 44.6463, -49.583 The coordinates after conversion to tuple are: (44.6463, -49.583) 




Get Solution for free from DataCamp guru