I am trying to populate fields with centred Easting/ Northing coordinates from a field of British National Grid grid references. I want to take different digits from the grid reference depending on its number of characters (precision). Without going into the details of BNG grid references too much, an example expression to take an Easting coordinate for me looks like this:
int(str(!Easting_1!)+str(!Grid_ref![2:7]))
If I enter this, or a slightly modified version for a different length grid reference, directly as the field calculator expression, it works fine. However, when I try to include a bunch of slightly modified versions of the above as if/else statements in the Code Block, I get an invalid syntax error:
I'm not sure what is going on as I am copying and pasting code from if/else statements that work fine for me elsewhere, just replacing the return value with 'int(str(!Easting_1!)+str(!Grid_ref![X:X]+"X"))', which is an expression that works fine when I use it to calculate a field directly, without the Code Block.
Any help much appreciated!
Solved! Go to Solution.
you have to pass Easting_1 to the function
reclass(!Grid_ref!, !Easting_1!)
def reclass(Grid_ref, Easting_1):
if (len(Grid_ref -- 12):
return int(str(Easting_1) + str(Grid_ref[2:7]))
etc
etc
The problem is the variables with the exclamation points in your code block. Those are only allowed in the function call, as they're not actually valid Python. It's an ArcGIS-specific implementation.
You first need to pass in that Easting attribute to your function call:
reclass(!Grid_ref!, !Easting_1!)
And then in your code block:
def reclass(grid_ref, easting):
if len(grid_ref) == 12:
return int(str(easting) + str(grid_ref[2:7]))
...
As an aside, you don't actually need parentheses around your if clauses like that in Python if they're on a single line, but it won't hurt anything to have them. That's really just a preference thing.
you have to pass Easting_1 to the function
reclass(!Grid_ref!, !Easting_1!)
def reclass(Grid_ref, Easting_1):
if (len(Grid_ref -- 12):
return int(str(Easting_1) + str(Grid_ref[2:7]))
etc
etc
Of course! Many thanks Dan for the swift response!
The problem is the variables with the exclamation points in your code block. Those are only allowed in the function call, as they're not actually valid Python. It's an ArcGIS-specific implementation.
You first need to pass in that Easting attribute to your function call:
reclass(!Grid_ref!, !Easting_1!)
And then in your code block:
def reclass(grid_ref, easting):
if len(grid_ref) == 12:
return int(str(easting) + str(grid_ref[2:7]))
...
As an aside, you don't actually need parentheses around your if clauses like that in Python if they're on a single line, but it won't hurt anything to have them. That's really just a preference thing.
Thanks for the clear description and tip about the if clause parentheses 🙂