Conditional replace function in Field Calculator

2170
5
06-20-2012 05:11 AM
BenjaminYoung
New Contributor
I'm trying to write an expression that will allow me to change the text of a string field based on it's values.

Here's what I have so far.

----

Dim output as String

IF [DUPLICATE] = "0"
THEN
output = replace( [DUPLICATE], "0", "CATEGORY 1")
end if

IF [DUPLICATE] = "1"
THEN
output = replace( [DUPLICATE], "1", "CATEGORY 2")
end if

IF [DUPLICATE] = "2"
THEN
output = replace( [DUPLICATE], "2", "CATEGORY 3")
end
----

Any help would be appreciated.
Tags (2)
0 Kudos
5 Replies
JimCousins
MVP Regular Contributor
A single "=" is an assignment. In order to do a comparison, use "==" a double equal sign. You could also nest these individual if statements with:
if [DUPLICATE] == "0":
output = replace( [DUPLICATE], "0", "CATEGORY 1")
elif [DUPLICATE] == "1":
output = replace( [DUPLICATE], "1", "CATEGORY 2")
....
0 Kudos
BenjaminYoung
New Contributor
Thanks but still not working. Is it something with the

if [DUPLICATE] == "0":
output = replace( [DUPLICATE], "0", "CATEGORY 1")

?

Tried that line by itself and returned an error.
0 Kudos
JasonScheirer
Occasional Contributor III
In the Field Calc, need to do !DUPLICATE! and not [DUPLICATE] in Python.
0 Kudos
JimCousins
MVP Regular Contributor
Also be mindful of indentation. My earlier post didn't show correct indentation after the if statement. Apologies for that.
0 Kudos
DarrenWiens2
MVP Honored Contributor
Firstly, you need to decide if you want to use VBScript or Python. You started with almost functional VBScript and have been slowly drifting into functional Python.

PYTHON:
In the expression box:
func(!DUPLICATE!)

Then, in the codeblock:
def func(dup):
    if dup == "0":
        return "CATEGORY 1"
    elif dup == "1":
        return "CATEGORY 2"
 


VBSCRIPT:
In the expression box:
result

Codeblock:
if [DUPLICATE] = 0 then
  result = "CATEGORY 1"
elseif [DUPLICATE] = 1 then
  result = "CATEGORY 2"
else
  result = [DUPLICATE]
end if
0 Kudos