Convert location coordinates to tuple in Python

When working with location data, you often need to convert coordinate strings into tuple format for mathematical operations or data processing. Python provides several methods to accomplish this conversion safely and efficiently.

Method 1: Using eval() (Not Recommended)

The eval() method can parse and execute string expressions, but it poses security risks ?

my_string = "67.5378, -78.8523"

print("The string is:")
print(my_string)

my_result = eval(my_string)

print("The coordinates after converting the string to tuple is:")
print(my_result)
print("Type:", type(my_result))
The string is:
67.5378, -78.8523
The coordinates after converting the string to tuple is:
(67.5378, -78.8523)
Type: <class 'tuple'>

Method 2: Using split() and tuple() (Recommended)

A safer approach using string splitting and type conversion ?

coord_string = "67.5378, -78.8523"

print("Original string:", coord_string)

# Split by comma and convert to floats
coords = tuple(float(x.strip()) for x in coord_string.split(','))

print("Converted tuple:", coords)
print("Type:", type(coords))
Original string: 67.5378, -78.8523
Converted tuple: (67.5378, -78.8523)
Type: <class 'tuple'>

Method 3: Using Regular Expressions

For more complex coordinate formats, regular expressions provide robust parsing ?

import re

coord_string = "Lat: 67.5378, Lon: -78.8523"

print("Original string:", coord_string)

# Extract numbers using regex
numbers = re.findall(r'-?\d+\.?\d*', coord_string)
coords = tuple(float(num) for num in numbers)

print("Extracted coordinates:", coords)
print("Type:", type(coords))
Original string: Lat: 67.5378, Lon: -78.8523
Extracted coordinates: (67.5378, -78.8523)
Type: <class 'tuple'>

Comparison

Method Security Flexibility Best For
eval() Unsafe High Never recommended
split() Safe Medium Simple comma-separated values
Regular expressions Safe High Complex or varied formats

Conclusion

Use split() with tuple() for simple coordinate strings. Avoid eval() due to security risks. Use regular expressions for complex parsing needs.

Updated on: 2026-03-25T17:29:25+05:30

556 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements