Skip to content
Related Articles

Related Articles

Python | Convert location coordinates to tuple

View Discussion
Improve Article
Save Article
  • Last Updated : 29 Apr, 2022

Sometimes, while working with locations, we need a lot of data which has location points in form of latitudes 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(). 

Python3




# 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))

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 separated as tuple elements. 

Python3




# 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))

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
Recommended Articles
Page :

Start Your Coding Journey Now!