4

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!

CodeSpatial
  • 830
  • 2
  • 10
  • 18

3 Answers3

11

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'
nmpeterson
  • 8,276
  • 33
  • 59
2

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')
-123.5701111111111
>>> dms2float('0:34:12.4')
0.5701111111111111
>>> dms2float('123:34:12.4')
123.5701111111111
Mike T
  • 42,095
  • 10
  • 126
  • 187
1

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]
nmpeterson
  • 8,276
  • 33
  • 59