开发者

Splitting a GPS Point into Latitude and Longitude Regular

Given the following string representation of a GPS point...

(40.714353, -74.005973)

How can I perform a string split开发者_开发技巧 to obtain both the latitude and longitude as separate tokens - without any superfluous characters (spaces and brackets) using Python?


You may use ast.literal_eval() to parse the string:

>>> import ast
>>> coord = "(40.714353, -74.005973)"
>>> ast.literal_eval(coord)
(40.714353000000003, -74.005972999999997)


You don't need regular expressions:

>>> str = "(40.714353, -74.005973)"
>>> tuple(float(x) for x in str.strip('()').split(','))
(40.714353, -74.005973)

If you want to have strings instead of numbers, use x.strip() instead of float(x).


A regular expression solution could be:

>>> import re
>>> m = re.match(r"^\(([-\d.]+), ([-\d.]+)\)$", str)
>>> m.group(1)
'40.714353'
>>> m.group(2)
'-74.005973'

This uses capture groups to extract the information.

See also the re documentation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜