Python | Convert location coordinates to tuple

Sometimes, while working with locations, we need a lot of data which has location points in form of latitutes and longitudes. These can be in form of a string and we desire to get tuple versions of same. Let’s discuss certain ways in which this task can be performed.

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

The combination of above functions can be used to perform this task. In this, we first split the two parts of coordinates into a list, apply float function to each of them using float() and map() and lastly it is converted to tuple using tuple().



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert location coordinates to tuple
# Using tuple() + float() + split() + map()
  
# Initializing string
test_str = "44.6463, -49.583"
  
# printing original string
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(', ')))
  
# printing result
print("The coordinates after conversion to tuple are : " + str(res))

chevron_right


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 the one-liner and recommended method to perform this particular task. In this, the eval(), internally detects the string and converts to floating point number seperated as tuple elements.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert location coordinates to tuple
# Using eval()
  
# Initializing string
test_str = "44.6463, -49.583"
  
# printing original string
print("The original string is : " + str(test_str))
  
# Convert location coordinates to tuple
# Using eval()
res = eval(test_str)
  
# printing result
print("The coordinates after conversion to tuple are : " + str(res))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.