如何用纬度和经度分隔字符串



我有一个带有纬度和经度的位置字符串。

location = "-40.20361-40.20361"

我想做的是将字符串分离为

lat = "-40.20361"
long = "-40.20361"

注意:位置也可以采用以下形式,所以我正在寻找一个无论符号如何都能工作的解决方案。

"+40.20361+40.20361"
"-40.20361+40.20361"
"+40.20361-40.20361"

谢谢。

您可以通过字符串操作(在-+上拆分字符串(或作为正则表达式来执行此操作。正则表达式的解决方案可能类似于:

>>> lat, lon = re.match(r'([+-][0-9]{1,3}.[0-9]+)([+-][0-9]{1,3}.[0-9]+)', '+40.20361-40.20361').groups()
>>> lat, lon
('+40.20361', '-40.20361')

正则表达式由CCD_ 3的两种模式组成。进一步细分:

([+-][0-9]{1,3}.[0-9]+)
^- match the prefix (i.e. + or -)
([+-][0-9]{1,3}.[0-9]+)
^--- between 1 and 3 (inclusive) repeats of the class in front,
so [0-9] repeated one to three times
([+-][0-9]{1,3}.[0-9]+)
^-- a literal dot (otherwise a dot means "any character")
([+-][0-9]{1,3}.[0-9]+)
^-- repeat the preceding character class at least once, so
at least one occurence of [0-9].

如果你想避免正则表达式,那就是我的解决方案:

def location_split (location):
lat=""
lon=""
split=False
for i, char in enumerate(location):
if char in "+-" and i!=0:
split=True
if split==False:
lat+=char
else:
lon+=char

return (lat, lon)
print (location_split("+40.20361+40.20361")) # ('+40.20361', '+40.20361')
print (location_split("-40.20361+40.20361")) # ('-40.20361', '+40.20361'
print (location_split("+40.20361-40.20361")) # ('+40.20361', '-40.20361')

最新更新