2

I have an access table that has a bunch coordinate values in degrees minutes seconds and they are formatted like this:

90-12-28.15

I want to reformat it like this:

90° 12' 28.15"

essentially replacing the dashes with the degrees minutes and seconds characters and a space between the degrees and minutes and another one between the minutes and seconds.

I'm thinking about using the 'Replace' function, but I'm not sure how to replace the first instance of the dash with a degree character (°) and space and then detect the second instance of the dash and place the minute characters and a space and then finally adding the seconds character at the end.

Any help is appreciated.

Mike

4 Answers 4

5

While regular expressions and split() are fine solutions, doing this with replace() is rather easy.

lat = "90-12-28.15"

lat = lat.replace("-", "° ", 1)
lat = lat.replace("-", "' ", 1)
lat = lat + '"'

Or you can do it all on one line:

lat = lat.replace("-", "° ", 1).replace("-", "' ", 1) + '"'
Sign up to request clarification or add additional context in comments.

1 Comment

Cool, I didn't know you could do that.
2

I would just split your first string:

# -*- coding: utf-8 -*-

str = '90-12-28.15'

arr = str.split('-')   
str2 = arr[0] +'° ' + arr[1] + '\'' +arr[2] +'"'

print str2

Comments

1

You might want to use Python's regular expressions module re, particularly re.sub(). Check the Python docs here for more information.

If you're not familiar with regular expressions, check out this tutorial here, also from the Python documentation.

import re

text = 'replace "-" in 90-12-28.15'
print(re.sub(r'(\d\d)-(\d\d)-(\d\d)\.(\d\d)', r'''\1° \2' \3.\4"''', text))
# use \d{1,2} instead of \d\d if single digits are allowed

Comments

0

The python "replace" string method should be easy to use. You can find the documentation here.

In your case, you can do something like this:

my_str = "90-12-28.15"
my_str = my_str.replace("-","°",1)# 1 means you are going to replace the first ocurrence only
my_str = my_str.replace("-","'",1)
my_str = my_str + "\""

1 Comment

The link you provided has no information on the replace method that I could find. The actual information is in the link on that page at the top String Methods which takes you here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.