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.

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Feb 18, 2017 at 0:00

1 Answer 1

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])
answered Feb 18, 2017 at 0:54
1
  • The UpdateCursor works great. I tried fiddling around with it previously and couldn't figure it out so thanks a lot. :) Commented Feb 20, 2017 at 18:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.