Skip to content

Field Calculator Python Slicing

Anthony Blackham edited this page Sep 17, 2021 · 4 revisions

When using the field calculator, parsing strings in various formats is a pretty common practise. Slicing strings is a little different than other parsing methods in that you are slicing in between characters rather than selecting a number of characters. The following is a simple graphic illustrating slicing:

 +---+---+---+---+---+---+
 | P | Y | T | H | O | N |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1   0 

Note that there are some syntax variances with pure python compared to arc python but the principles are the same, as this is a GIS-centric blog I will use examples from the syntax within the field calculator

Return first character:

!field![1:]

Result: P

Return last 5 characters:

!field![-5:]

Result: YTHON

Return characters 2 and 3:

!field![1:3]

Result: YT

Remove last two characters:

!field![:-2]

Result: PYTH

Remove everything before first space:

' '.join(!field!.split(' ')[1:])

Remove everything after first space:

' '.join(!field!.split(' ')[:1])