如何解析带负号的字符串并保留负号?Python经纬度代码求助
Hey there! Let's tackle your problem of parsing latitude/longitude strings while keeping negative signs intact. First, let's look at what's going on with your current code, then improve it for reliability.
Why Your Current Code Might (or Might Not) Be Working
Your existing code uses re.split() to extract values, and actually, it should already preserve the negative sign for longitude. Let's test it with your sample input:
latlonginput = 'Latitude=28.0358214, Longitude=-82.59970229999999, Accuracy=4232m' import re 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]) print(geo_long) # Output: -82.59970229999999
As you can see, the negative sign is preserved here. But this approach is fragile—if the order of parameters changes, or there's extra whitespace, it might break unexpectedly.
A More Robust Solution Using Regex Capture Groups
Instead of splitting the string, use regex to directly capture the values you need. This is more reliable and explicitly handles negative numbers:
latlonginput = 'Latitude=28.0358214, Longitude=-82.59970229999999, Accuracy=4232m' import re # Regex pattern to capture latitude, longitude, and accuracy pattern = r'Latitude=([-+]?\d+\.\d+),\s*Longitude=([-+]?\d+\.\d+),\s*Accuracy=(\d+m)' match = re.search(pattern, latlonginput) if match: geo_lat = match.group(1) geo_long = match.group(2) accuracy = match.group(3) geo_coord = f"{geo_lat},{geo_long}" latlong = f'Detected Lat/Long: {geo_coord}\n' latlong += f'Accuracy: {accuracy}\n' print(latlong) else: print("Failed to parse the latitude/longitude string.")
Let's Break Down the Regex:
([-+]?\d+\.\d+): Captures a number that may start with-or+, followed by digits, a decimal point, and more digits (perfect for lat/long values with signs).\s*: Matches any amount of whitespace (handles inconsistent spacing in the input string).(\d+m): Captures the accuracy value with its unit.
Key Benefits of This Approach:
- Guarantees sign preservation: The regex explicitly includes
[-+]?to capture positive/negative signs without fail. - More resilient: Works even if there's extra whitespace or minor formatting variations in the input.
- Clearer intent: The code directly shows what values you're extracting, making it easier to maintain or modify later.
If your original code was having issues with negative signs, it might have been due to a truncated line (your code ends with latlong = latlong...) or unexpected input formatting. The regex method avoids those edge cases entirely.
内容的提问来源于stack exchange,提问作者paulmiller3000

