I have this location string with latitude and longitude.
location = "-40.20361-40.20361"
What I would like to do is separate the string as
lat = "-40.20361"
long = "-40.20361"
Note: The location can also take the following forms so I'm looking for a solution that works regardless of the notation.
" 40.20361 40.20361"
"-40.20361 40.20361"
" 40.20361-40.20361"
Thanks.
CodePudding user response:
You can do it either with string manipulation (split string on -
and
) or as a regular expression. A regular expression solution could be something like:
>>> 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')
The regular expression consists of two patterns of '([ -][0-9]{1,3}\.[0-9] )
. To break this down further:
([ -][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].
CodePudding user response:
If you want to avoid regular expressions, thats my solution:
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')