Reputation: 744
I have a list of latitude and longitude as follows:
['33.0595° N', '101.0528° W']
I need to convert it to floats [33.0595, -101.0528]
.
Sure, the '-' is the only difference, but it changes when changing hemispheres, which is why a library would be ideal, but I can't find one.
Upvotes: 1
Views: 764
Reputation: 309
The following is the way I would solve the issue. I think the previous answer uses regex that might prove to be a bit slower (would need benchmarking).
data = ["33.0595° N", "101.0528° W"]
def convert(coord):
val, direction = coord.split(" ") # split the direction and the value
val = float(val[:-1]) # turn the value (without the degree symbol) into float
return val if direction not in ["W", "S"] else -1 * val # return val if the direction is not West
converted = [convert(coord) for coord in data] # [33.0595, -101.0528]
Upvotes: 1
Reputation: 8298
You can wrap the following code in a function and use it:
import re
l = ['33.0595° N', '101.0528° W']
new_l = []
for e in l:
num = re.findall("\d+\.\d+", e)
if e[-1] in ["W", "S"]:
new_l.append(-1. * float(num[0]))
else:
new_l.append(float(num[0]))
print(new_l) # [33.0595, -101.0528]
The result match what you expect.
Upvotes: 1