OK, I know that this is Python 101, but I can't seem to figure it out.

I have a function setup that will return a string, specifically an azimuth in DMS. I need to take the return values and pull out only the value that appears prior to an ":"

So I may get a value x = 123:34:12.4

I need x to then equal 123 and use that to updateRow in an attribute table.

As usual... THANKS!


The string split() function is what you're looking for:

x_list = '123:34:12.4'.split(':')  # Converts string into list of sub-strings separated by ':', i.e. ['123', '34', '12.4']
x = x_list[0]  # The first item in the list, i.e. '123'
  • 7
    Or: (d, m, s) = '123:34:12'.split(':') – gsherman Apr 19 '13 at 17:45
  • 6
    @gsherman you can omit the parentheses around d, m, s as the commas themselves are all that are needed to perform the sequence unpacking. – blah238 Apr 19 '13 at 21:20

If you want to determine the precise decimal degrees equivalent, here is a useful function given your format:

from math import copysign

def dms2float(dms):
    '''Returns decimal degrees from "[-]dd:mm:ss.s" string'''
    d, m, s = [float(x) for x in dms.split(':')]
    return copysign(1, d) * (abs(d) + m / 60 + s / 3600)

and to use it:

>>> dms2float('-123:34:12.4')
>>> dms2float('0:34:12.4')
>>> dms2float('123:34:12.4')

More syntax sugar:

x = "123:34:12.4".split(":")[0]

It's just a shorter version of this:

# split the string into a list. 
# In Python, a string is 
# an object!
myList = "123:34:12.4".split(":")
print myList  # prints: ["123","34","12.4"]

# Set x to the first item in myList
# index of first item is 0
x = myList[0]
print x  # prints: "123"

# Instead of using myList,
# we can just stack the output 
# of split() into x
x = "123:34:12.4".split(":")[0]

Not the answer you're looking for? Browse other questions tagged or ask your own question.