Question

I am new to python scripting and I mainly use it in ArcGIS 10. My script is supposed to reformat a string within the Field CINTP1. An example would be '000000100' and return '1.00'. I have imported it into a toolbox to run on a selected record within the table 'MAPCHAR'. The error I keep recieveing is:

: ERROR 000539: Error running expression: removeLeadingZeros("000000100") : global name 're' is not defined Failed to execute (CalculateField).

Failed to execute (Script).

Here is my script:

import arcpy, re, sys, string, os

MAPCHAR = "MAPCHAR"

CINPT1 = "CINPT1"

expression = "removeLeadingZeros(!CINPT1!)"
codeblock = """def removeLeadingZeros(myValue):
    newValue = re.sub('^0+',"",myValue)

    valueList = list(newValue) #convert newValue to List
    valueList.insert(-2, '.') #insert the '.' characater int the list at the -2 position

    newValue = "".join(valueList) #join back to create the new  updated string

    myvalue = newValue"""

arcpy.CalculateField_management(MAPCHAR, CINPT1, expression, "Python", codeblock)

Any help would be appreciated..thanks,

Was it helpful?

Solution

You should have your import statements in the below codeblock.. So add an import re as the first line in codeblock: -

codeblock = """import re
    def removeLeadingZeros(myValue):
        newValue = re.sub('^0+',"",myValue)

        valueList = list(newValue) #convert newValue to List
        valueList.insert(-2, '.') #insert the '.' int the list at the -2 position

        newValue = "".join(valueList) #join back to create the new  updated string

        myvalue = newValue"""

OTHER TIPS

It looks like you're running codeblock in the arcpy namespace. If arcpy doesn't have import re in it, codeblock wont work.

incidentally, you dont need regex to remove leading zeros-- just convert to an int. Classic example of using a wrench to hammer a nail.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top