0

I have this function for labeling layers using arcpy This function works totally fine but I have the field hardcoded into the function

def label(wah):
    for lyr in arcpy.mapping.ListLayers(mxd):
        if lyr.name == wah:
            if lyr.supports("LABELCLASSES"):
                for lblClass in lyr.labelClasses:
                    lblClass.expression = "[field]"
                    lblClass.showClassLabels = True
                    lyr.showLabels = True

i want to be able to change the labeling expression for every layer. I have tried this way below, but the labeling does not show up at all.

def label(wah, field):
    for lyr in arcpy.mapping.ListLayers(mxd):
        if lyr.name == wah:
            if lyr.supports("LABELCLASSES"):
                for lblClass in lyr.labelClasses:
                    lblClass.expression = "'["+field+"]'" 
                    lblClass.showClassLabels = True
                    lyr.showLabels = True

Can someone help me fix my code. i am aware many programmers use .format instead of just using string with the + sign. what is the advantage of that?

when i call the function should it be

label("layer", field)

or

label("layer", "field")

1 Answer 1

2

I'm not sure where your single quotes came from in the expression. They aren't there in the hard-coded version, and they aren't needed.

Change:

lblClass.expression = "'["+field+"]'" 

to:

lblClass.expression = "["+field+"]" 

Or, better yet:

lblClass.expression = '[{0}]'.format(field)

The string formatting is prettier (especially with longer string concatenations) and more flexible (no need to convert, e.g., integers to strings).

As for how to call your function, it depends. If you've assigned your field name to a variable named field, then send it without quotes. If you're doing it wrong, you'll know because you'll get a NameError saying that name 'field' is not defined...that is, unless you've been misled to use try/except around all your code.

2
  • thanks okay so when i call the function the 2nd argument I have as field should not be in quotes..?
    – ziggy
    Commented May 26, 2016 at 16:01
  • It should be in quotes if you are calling it directly or without, if you have a variable saved something like field = "field".
    – yanes
    Commented May 26, 2016 at 16:29

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.