How to parse any lat/lon string in Python using GeoPy

When working with user-entered coordinates, you often have strings like N 48° 06.976 E 11° 44.638, 48°06'58.6"N 11°44'38.3"E or N48.116267, E11.743967. These lan/lon coordinates come in many, many different formats which makes it rather hard to parse in an automated setting.

One simple solution for Python is to use geopy which provides access to a bunch of Online services such as ArcGIS. These services make it easy to parse pretty much any form of coordinate. You can install geopy using

pip install geopy

Note that Nominatim does not work for the pure coordinates use case – it parses the coordinates just fine but will return the closest building / address.

from geopy.geocoders import ArcGIS

geolocator = ArcGIS()

result = geolocator.geocode("N 48° 06.976' E 11° 44.638'")

In case the coordinates can’t be parsed, result will be None

After that, you can work with result, for example, in the following ways:

print(result) will just print the result:

>>> print(result)
Location(Y:48.116267 X:11.743967, (48.11626666666667, 11.743966666666667, 0.0))

You can extract the latitude and longitude using result.latitude and result.longitude.

>>> print(result.latitude, result.longitude)
(48.11626666666667, 11.743966666666667)

For other ways to work with these coordinates, refer to the geopy documentation.