0

Here is what I have

import arcpy

inputFC = arcpy.GetParameterAsText (0)         #Feature Class  
inputField = arcpy.GetParameterAsText (1)      #Field to manipulate  
inputChar = arcpy.GetParameterAsText (2)      #The character(s) I wish to replace  
replChar = arcpy.GetParameterAsText (3)        #The character(s) I wish to replace them with  

arcpy.CalculateField_management(inputFC, inputField, !inputField!.replace(inputChar, replChar), "PYTHON_9.3")

I am trying to use the "CalculateField_management" tool with a variable instead of a direct field for the 3rd input like I am with the first 2, but I can't seem to fit it in with the expression. I want it to take the value of the existing string and replace the characters I desire. How is the expression supposed to be written?

I have tried a variety of ways and can't figure it out.
For example: !inputField!.replace, '"!inputField!'".replace, inputField.replace, '"inputField"'.replace, etc.

2

You're on the right track with '"!inputField!'".replace, just needed some variable substitution. Otherwise, you'd just be operating on the value contained by the variable, eg "myField".replace('abc', 'def') which doesn't have much meaning.

So, you need to create a string, which is easy with string formatting.

inputField= 'myField'
inputChar = 'abc'
replChar = 'def'

expr = "!{field}!.replace('{old}', '{new}')".format(field=inputField,
                                                    old=inputChar,
                                                    new=replChar)

arcpy.CalculateField_management(inputFC, inputField, expr, "PYTHON_9.3")

>>> expr
"!myField!.replace('abc', 'def')" 
>>> print(expr)
!myField!.replace('abc', 'def')

Tricky to write, so I prefer cursors:

with arcpy.da.UpdateCursor(inputFC, inputField) as cursor:
     for row in cursor:
         new = row[0].replace(inputChar, replChar)
         cursor.updateRow([new])
  • The UpdateCursor works great. I tried fiddling around with it previously and couldn't figure it out so thanks a lot. :) – Maxwell Tougas Feb 20 '17 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.