[GIS] How to extract portion of a string for a field value

arcgis-desktopmodelbuilderpythonstring

This is simple but driving me mad. I am using Modelbuilder to iterate through a folder of feature classes, and need to add a field that extracts a portion of the filename.

Example:
CF0140r01.shp
I want to add a field to the its table that is titled Image, and wish to just extract the portion of the file name from character positions 3-6 so the resulting field has a value of 0140

I have LOTS of these files, and each one has the Image number embedded in the file name, always at the same positions (two leading Text characters, 4 digits for Image number, three trailing characters with more information)

Best Answer

I haven't really used model builder too much (usually just hack my way through a model to run some script I made), because I usually use ArcPy for stuff. But maybe I could help you go in the right direction.

I would suggest to use the Add Field tool from toolbox datamanagement->Fields->Addfield. then hook the output of that up to calculate field from the same box. Now in there if you change Expression type to python, and then use the slice operator [:] to choose the substring of the name. so 3-6 would be 2-5 since python strings start indexing at 0.

However I'd know how to get the name of the file using python and the os library. I'm not familiar with how to read the current shape file from model builder I can try to look at it later when I'm back at my desk. And try to build out a rough one if no one can come along with better insight.

Related Question