0

I'm trying to define a function in python to replace some items in a string. My string is a string that contains degrees minutes seconds (i.e. 216-56-12.02)

I want to replace the dashes so I can get the proper symbols, so my string will look like 216° 56' 12.02"

I tried this:

def FindLabel ([Direction]):
  s = [Direction]
  s = s.replace("-","° ",1) #replace first instancwe of the dash in the original string
  s = s.replace("-","' ") # replace the remaining dash from the last string

  s = s + """ #add in the minute sign at the end

  return s

This doesn't seem to work. I'm not sure what's going wrong. Any suggestions are welcome.

Cheers, Mike

2
  • 1
    Uh... then what does it do? Commented Oct 25, 2012 at 21:58
  • Given that the very first line is a syntax error in either Python2 or Python3 (if you're trying to decompose-match the arguments, that's not how you do it), it's going to be hard for anyone to figure out what you're actually attempting. Commented Oct 25, 2012 at 23:31

2 Answers 2

2

Honestly, I wouldn't bother with replacement. Just .split() it:

def find_label(direction):
    degrees, hours, minutes = direction.split('-')

    return u'{}° {}\' {}"'.format(degrees, hours, minutes)

You could condense it even more if you want:

def find_label(direction):
    return u'{}° {}\' {}"'.format(*direction.split('-'))

If you want to fix your current code, see my comments:

def FindLabel(Direction):  # Not sure why you put square brackets here
  s = Direction            # Or here
  s = s.replace("-",u"° ",1)
  s = s.replace("-","' ")

  s += '"'  # You have to use single quotes or escape the double quote: `"\""`

  return s

You might have to specify the utf-8 encoding at the top of your Python file as well using a comment:

# This Python file uses the following encoding: utf-8
Sign up to request clarification or add additional context in comments.

2 Comments

Hey BLender, thanks for replying. I like your syntax. I'm having further issues though. First off, the reason why 'Direction' is in square brackets is because it is a field in an access table. I'm cursoring through each record to change the format of the string. I've tried both of your examples above and not I get an error returning saying 'FindLabel' is not defined?
I renamed your function to find_label.
1

this is how i would do it by splitting into a list and then joining back:

s = "{}° {}' {}\"".format(*s.split("-"))

Comments

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.