1

I have a point file that has a field in it that lists all the streets at an intersection, eg) 1st St & A blvd & 2nd Ave etc

I want to be able to separate each street out individually into its own separate field.

I have some Python code I managed to field to use in field calculator that seems to work until it hits a field that doesnt have a 3rd street (and thus a third '&' symbol) so its erroring out.

How can I make it pass over these instances so it can run successfully? I think its erroring out on the 3rd passes when it comes across field with only 2 streets, eg 1st Ave & 2nd Ave

Code is below

Pre-Logic

def getField(inField):
  if inField is None:
    return None
  else:
    return inField.split(' & ')[0]




getField ( Names! )

Edit

This is basically what I want to do, a simple formula in excel seperates them, just trying to find the Python equivalent in ArcMAp

https://ibb.co/rGHVvT1

0

1 Answer 1

2

You are not showing all your code. But you could check if split list is to short, and if so then extend with empty string. Example:

a = '1st St & A blvd'
s = a.split(' & ')
print s

diff = 3-len(s)
if diff != 0:
    s.extend([' ']*diff)

print s

Outputs:

['1st St', 'A blvd']
['1st St', 'A blvd', ' ']

Or use try/except:

a = [1,2]
try:
    print a[2]
except IndexError: #a[2] is not possible, will give Indexerror, then dont do anything:
    pass

You could automate everything if you dont mind skipping field calculator:

import arcpy

fc = r'C:\GIS\ArcMap_default_folder\Default.gdb\ak_riks'
splitfield = ['KOMMUNNAMN']

rows = [i[0] for i in arcpy.da.SearchCursor(fc,splitfield)] #List all splitfield values
fields_needed = max([len(r.split('a')) for r in rows]) #Find out how many new fields are needed
prefix = 'Split_' #What to name new fields

newfields = []
for f in range(0,fields_needed):
    newfield = prefix+str(f)
    newfields.append(newfield)
    arcpy.AddField_management(in_table=fc, field_name=newfield, field_type='TEXT', field_length=20) #Adjust field length

with arcpy.da.UpdateCursor(fc, splitfield+newfields) as cursor:
    for row in cursor:
        newdata = row[0].split('a')
        diff = len(newfields) - len(newdata)
        if diff > 0:
            newdata = newdata+[' ']*diff
        else:
            newdata = newdata[:len(newfields)]
        row[1:] = newdata
        cursor.updateRow(row)

enter image description here

Your Answer

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

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