paulmiller3000
paulmiller3000

Reputation: 461

Parse string with minus sign, retain minus sign

I have the following code:

latlonginput = 'Latitude=28.0358214, Longitude=-82.59970229999999, Accuracy=4232m'

import re

try:
    #latlonginput = input['latlong']
    geo_lat = format(re.split(r'(Latitude=|,)', latlonginput)[2])
    geo_long = format(re.split(r'(Longitude=|,)', latlonginput)[2])
    accuracy = format(re.split(r'(Accuracy=)', latlonginput)[2])
    geo_coord = geo_lat + ',' + geo_long
    latlong = 'Detected Lat/Long: '+ geo_coord + '\n'
    latlong = latlong + 'Accuracy: ' + accuracy + '\n'
    latlong = latlong + 'Maps: placeholder'
except:
    latlong = None

return {'lat_long': latlong }

In this case, with longitude being a negative value, it omits the negative. For example, this is the result:

Detected Lat/Long: 28.0358214,
Accuracy: 4232m
Maps: placeholder

I need to allow for negatives in either latitude or longitude. How can I adjust to do so?

Thanks, Noob

Upvotes: 0

Views: 448

Answers (3)

Morse
Morse

Reputation: 9144

You just need to change second line to (index of 4 instead of 2)

geo_long = format(re.split(r'(Longitude=|,)', latlonginput)[4])

I prefer @chepner's answer to save processing time.

Output

Detected Lat/Long: 28.0358214,-82.59970229999999
Accuracy: 4232m
Maps: placeholder

Upvotes: 0

user3483203
user3483203

Reputation: 51165

You can use a regular expression with optional matching to check for negative signs in front of your desired numbers.

Also if this is your format of your strings, using re.split is not needed, you can simply match.

If those numbers are the only numbers present in your string, you can simply use:

In [11]: re.findall(r'-?\d+\.?\d+m?', s)
Out[11]: ['28.0358214', '-82.59970229999999', '4232m']

If you want to make this more robust, you could match that entire format:

import re

rgx = r'Latitude=(-?\d+\.\d+).*Longitude=(-?\d+\.\d+).*Accuracy=-?(\d+m)'
s = 'Latitude=28.0358214, Longitude=-82.59970229999999, Accuracy=4232m'

lat, long, accuracy = re.findall(rgx, s)[0]
print('Lat/Long: {}, {}\nAccuracy: {}'.format(lat, long, accuracy))

Output:

Lat/Long: 28.0358214, -82.59970229999999
Accuracy: 4232m

Upvotes: 7

chepner
chepner

Reputation: 531918

Regular expressions are overkill for this; just split the string on ", " first, then split each element on "=":

>>> dict(x.split('=') for x in latlonginput.split(', '))
{'Latitude': '28.0358214', 'Longitude': '-82.59970229999999', 'Accuracy': '4232m'}

Then use the dictionary as necessary.

Upvotes: 5

Related Questions