[GIS] Concatenating fields with label expressions using Python

arcgis-10.2arcgis-desktoplabelingpython

I am trying to combine three numeric fields together for a feature's label. I only want to label the feature if it is over 0. The labeled numbers need to be separated a dash ("-"). This is what I attempted to use as the label expression in ArcMap 10.2:

def FindLabel ( [a1], [a2], [a3] ):
    if ([a3]) == 0 and int([a2]) == 0 and ([a1]) == 0:
        label = " "
    elif ([a3]) == 0 and int([a2]) == 0
        label = [a1]
    elif ([a3]) == 0
        label = [a1] + "-" + [a2]
    else:
        label = [a1] + "-" + [a2] + "-" + [a3]
    return label

Best Answer

This function doesn't need to be too complex. Convert the items you want into a list, then join the result.

def FindLabel([A1], [A2], [A3]):
    args = [A1, A2, A3]
    items = [str(x) for x in args if bool(x) and int(x) > 0]
    if any(items):
        return '-'.join(items)
    else:
        return ' '

If this were proper Python, you would normally use *args to accept any number of arguments into a list.

Related Question