[GIS] Field Calculator Python Expression Issues

arcgis-desktoperror-000539field-calculatormodelbuilderpython

I'm pretty new to Python and this is my first post on this forum so I could use some help. I am currently attempting to run some code in the Field Calculator in a model in order to replace string characters (hyphen, period, space) with an underscore ('_'). Here's what I have now.

def customReplace(Layer):
repList = ['-', ' ', '.'];
rep = '_'
for repList in Layer:
    return Layer.replace(repList, rep)
else:
    return Layer

Im getting a syntax error: ERROR 000539: SyntaxError: unexpected EOF while parsing (, line 1)
Failed to execute (Calculate Field (2)).

Anybody out there give me a hand?

By the way, I defined the above function in the pre-logic script code area and I'm calling it via

customReplace( !Layer! )

Best Answer

I am not completely sure to understand the aim of your script, but here are some comments

def customReplace(fieldV): # you must indent after your def
    repList = ['-', ' ', '.'] #remove the ;
    rep = '_'
    b=fieldV
    for old in repList: #I guess you want to replace the values in replist
        b = b.replace(old, rep) #here you need return, not print
    return b #no need to use else, but you must unindent

note that you need to put the function in a code block and call it with the name of the field

customReplace(!Layer!)

Related Question