Pythn to TextWrap

641
5
Jump to solution
09-17-2013 10:39 AM
ReneeRafferty
New Contributor II
I am using MapTips (Layer Properties > Display > Display Expression).  I would like to use the advanced expression window to write a script using Python TextWrap.  Field string needs to be wrapped +-40 characters with no word split.  Attribute field is named BODY.  Unfortunately, I find the python.org page (syntax/example) much harder to read than ESRI's.  Has anyone attempted this?

def FindLabel ( [Body] ):   return [Body]
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
MattSayler
Occasional Contributor II
Try this:
from textwrap import fill def FindLabel([BODY]):     x = fill([BODY],40)     return x


It should preferentially break lines at whitespace and dashes without any kind of intervention according to the doc.

Might need to move the 'from/import' inside the function:
def FindLabel([BODY]):     from textwrap import fill     x = fill([BODY],40)     return x

View solution in original post

0 Kudos
5 Replies
MattSayler
Occasional Contributor II
Try this:
from textwrap import fill def FindLabel([BODY]):     x = fill([BODY],40)     return x


It should preferentially break lines at whitespace and dashes without any kind of intervention according to the doc.

Might need to move the 'from/import' inside the function:
def FindLabel([BODY]):     from textwrap import fill     x = fill([BODY],40)     return x
0 Kudos
ReneeRafferty
New Contributor II
The first one worked great!  The only thing I would change:  The left justification butts up against the label box.  But it does wrap nicely.  Thanks, Matt!
0 Kudos
MattSayler
Occasional Contributor II
The first one worked great!  The only thing I would change:  The left justification butts up against the label box.  But it does wrap nicely.  Thanks, Matt!


Are you using a text background with the label (Advanced Text tab in properties)? The Balloon and Line Callout types have margin settings.
0 Kudos
ReneeRafferty
New Contributor II
Matt, I'm not using a Properties > Label.  This is a maptip that you hover your cursor over and it gives you the body of text.  I am using maptips are under Properties > Display.  Have attached an example of lack of margin.
0 Kudos
MattSayler
Occasional Contributor II
Hhmm, could add spaces to pad things. I'm still on 10.1, so couldn't test using python, but it looked like the tooltip would keep the extra space when using VBScript. Kind of a hacky way to do it, but I'm not seeing a way to adust padding for tool tips.

To accomplish this, use 'wrap' instead of 'fill', which returns a list containing each line, instead of the whole block of text. That will let you add a space to each line before adding it to the final block of text.
from textwrap import wrap
def FindLabel([BODY]):
    y = ""
    x = wrap([BODY],40)
    for item in x:
        y += " " + item + "\n"
    return y
0 Kudos