I have the following script that is used with a script tool to truncate each word in an input string and output the result to another field. There is an input parameter for the length of the truncation.
import arcpy
arcpy.env.overwriteOutput = True
# Prelogic used to pass through for calculating truncated name values
codeblock = """
def nmshort(stname,stnum):
s = stname.split()
s2 = s[:] = [elem[:stnum] for elem in s]
s3 = ' '.join(s2)
if s3 == stname:
return None
else:
return s3
""" # Finished code block
try:
# Set input parameters
inFC = arcpy.GetParameterAsText(0)
inName = arcpy.GetParameterAsText(1)
inNameShort = arcpy.GetParameterAsText(2)
inNumber = arcpy.GetParameterAsText(3)
# set expression for field calculation to variables
expression = "nmshort(!{0}!, {1})".format(inName,int(inNumber))
# perform field calculation
arcpy.AddMessage("Calculating truncated strings for values in input name field")
arcpy.CalculateField_management(inFC, inNameShort, expression, "PYTHON_9.3", codeblock)
arcpy.AddMessage("Calculation complete")
except:
arcpy.AddError("Could not complete the calculation")
arcpy.AddMessage(arcpy.GetMessages())
How would I accomplish this same calculation using a cursor instead of CalculateField? I'm using ArcGIS 10.0 so I won't be able to use the data access cursors. I've used cursors successfully involving simpler expressions (one line'ers) but I can't figure out how to do it for multiple process steps.
I applied Paul's answer as follows:
import arcpy
arcpy.env.overwriteOutput = True
# Prelogic used to pass through for calculating truncated name values
def nmshort(stname,stnum):
s = stname.split()
s2 = s[:] = [elem[:stnum] for elem in s]
s3 = ' '.join(s2)
if s3 == stname:
return None
else:
return s3
try:
# Set input parameters
inFC = arcpy.GetParameterAsText(0)
inName = arcpy.GetParameterAsText(1)
inNameShort = arcpy.GetParameterAsText(2)
inNumber = arcpy.GetParameterAsText(3)
# set expression for field calculation to variables
arcpy.AddMessage("Calculating truncated strings for values in input name field")
cursor = arcpy.UpdateCursor(inFC)
for row in cursor:
row.setValue(inNameShort, nmshort(inName,int(inNumber)))
cursor.updateRow(row)
del row, cursor
arcpy.AddMessage("Calculation complete")
except:
arcpy.AddError("Could not complete the calculation")
arcpy.AddMessage(arcpy.GetMessages())
The values all come back as "PLAC" for each row. "PLACENAME" is the field name that was used as the input.