2

I have a field named "ZIP" which has the zip code information for numerous records. Some of them have 9 numbers, but I only want them to have the first 5. What should my Pre-Logic Script look like to Field Calculate removing the last 4 numbers in this field?

Here is an image of the Field Calculator and the field:

enter image description here

5
  • In python you can use the simple expression: !ZIP![0:4]. No code block necessary.
    – Jyler
    Commented Apr 13, 2016 at 16:23
  • I agree, but this is giving me a geoprocessing error. Commented Apr 13, 2016 at 16:44
  • Got your radio button switched to Python? Also, don't include that period after the ].
    – Jyler
    Commented Apr 13, 2016 at 16:45
  • Yes and I did not include the period. Commented Apr 13, 2016 at 16:49
  • 1
    Is ZIP a field alias by chance? Or conversely, you might disable your code block.
    – Jyler
    Commented Apr 13, 2016 at 17:57

2 Answers 2

4

Use the string indices. Instead of creating a whole function, just do something like:

!ZIP![:5] --> basically grab everything from 0 index up to but not including the 5th index.

So it only grabs the indices 0,1,2,3,4.

Check out this tutorial for more information.

If there are more than 5 it will just grab the first 5. If there are 5 exact, it will grab them.

1
  • 2
    in the field calculator it'll probably be something like !ZIP![:5] I think
    – Midavalo
    Commented Apr 13, 2016 at 18:28
2

If the field is numeric, Python expression:

!zip![:4]

will fail.

It is easier to use vb script option:

left([zip],5)

This will populate output field of numeric and text type.

2
  • That's it! It is not a string, so that python expression does not work. Thanks! Commented Apr 13, 2016 at 20:24
  • It will work with some modification, e.g. if output field is numeric it's going to be float(str(!ZIP)[:4])
    – FelixIP
    Commented Apr 13, 2016 at 20:30

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.