[GIS] Splitting string in Python parser of ArcGIS Field Calculator

arcgis-10.0arcgis-desktopfield-calculatorpython-parser

I am trying to use Python to split a string field into three new fields at the separator " – ". The field is in the format "a – b – c". So I initially had this in the field calculator for newFieldA:

!myField!.partition(" - ")[0]

This gave me the value a in newFieldA. Similarly, I calculated newFieldB and newFieldC. After a more experienced Python user took a look at it, this was the final result:

' ' if !myField! == 'NULL' else !myField!.split(' - ')[0]

The test for NULL was put in because there were some NULL values throwing errors. Each of the three fields were calculated using this code, just the index was changed (0, 1 or 2).

My problem now is, after changing spelling errors in myField, I tried to split the field again, using the exact same code which worked previously. It now fails to run, giving the error of "wrong field name or unbalanced quotation marks". I am definitely using the correct field, and the quotation marks are not unbalanced. Also, I literally copied and pasted this from the code I used previously, so I don't see why it would be failing now. I feel like I'm missing something really simple. Does anyone have any ideas?

**edit** I've placed the following in the codeblock

define splitField(value):
' ' if value Is None
else:
  value.split(' - ')[0]

and in the expression window

splitField(!myField!)

I am getting a syntax error on line 1, I have not been using Python long enough to see what it could possibly be, as that looks right to me. Does anyone have a suggestion to make the code better?

edit I'm working with crime data, so in the field SUBACTION I have "Policing – Theft – Fraud". I then created three fields MANDATE, CATEGORY, and OFFENCE. The end result should be "Policing" in MANDATE, "Theft" in CATEGORY and "Fraud" in OFFENCE. I changed the codeblock to

def splitField(value):
  ' ' if !SUBACTION! == 'NULL'
      else:
        value.split(' - ')[0]

It is now giving a syntax error in line 2.

Best Answer

if !myField! == 'NULL' will not test for a null value. That will test a for a string equal to 'NULL'. Use:

if !myField! is None:

To accomlish your task, define a python function in the pre-logic code block and use that function in the expression window. The following code sample pulls the first token from a '-' delimited string.

enter image description here

Related Question