[GIS] Field Calculator expression to replace string only if it occurs

arcgis-10.1arcgis-desktopfield-calculatorpython

I have two fields (STREET1 & AKA_STREET_TEST1).

I'm having a problem creating a simple IF THEN Python statement in the Field Calculator box. I've been searching the threads for a similar example but to no avail. Basically the formula would work something like this.

If STREET1 contains "AVENUE", calculate AKA_STREET_TEST1 to "AVE",
ELSE leave it blank

(example below)

database_sample
Below is my feeble attempt at creating the if-then statement.

FieldCalculator_sample

Best Answer

A couple things to note:

Your code block is currently taking two arguments, but you really only need to take one. AKA_STREET_TEST1 is the result you want, not something that Calc() will consider when calculating. So your expression should be Calc(!STREET1!) -- because you want the function Calc to do something using the information from field STREET1, and that value will then be assigned to AKA_STREET_TEST1.

You can use a simple, one-line operation with Python's string.replace function, which essentially incorporates your if-then logic automatically. If AVENUE is in the string, it will be replaced with AVE. If AVENUE isn't there, it returns nothing and should leave the attribute empty.

def Calc(value):
    if "AVENUE" in value:
        return value.replace('AVENUE','AVE')