Split a label over several lines, using commas, in python

2965
5
Jump to solution
05-24-2016 11:32 PM
BenVan_Kesteren1
Regular Contributor

Hi All,

I am trying my hand at using python to modify my labeling to suit.

I have a column which contains peoples names, this column can contain between one and four names, all separated by a comma. See sample data here:

Currently when I label based on this column it looks pretty boring, what I would like is to split the names onto a new line, based on the comma. So essentially I want to find the comma, and insert a new line with the next name on it.

This is what it currently looks like, and the code:

def FindLabel ([BENVA.%Burial_Data.NAM], [SDE_SPATIAL.GISADMIN.waugh_road_graves.GIS_Authority_Link]   ):
  na = [BENVA.%Burial_Data.NAM]
  if na is None:
    na = [SDE_SPATIAL.GISADMIN.waugh_road_graves.GIS_Authority_Link]
  return na

Does anyone have any sample code they could provide that would achieve this? Alternatively give me some guidance as to how one would go about this???

Thanks very much everyone.

0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

Since users have a bad habit of adding extra whitespace either before or after commas, I typically use a strategy of splitting, stripping, and rejoining the string so the stacked labels line up nicely.  Borrowing from Neil Ayres​'s example:

>>> na = "Fred ,Charlie, Neil"
>>> na
'Fred ,Charlie, Neil'
>>> print na.replace(",", "\n")
Fred
Charlie
 Neil
>>> print "\n".join(s.strip() for s in na.split(","))
Fred
Charlie
Neil
>>>

View solution in original post

5 Replies
NeilAyres
MVP Frequent Contributor

You could try something like this

>>> na = "Fred, Charlie, Neil"
>>> print na.replace(",", "\n")
Fred
 Charlie
 Neil
FC_Basson
MVP Regular Contributor

Just use the replace function to replace the commas with line breaks

def FindLabel ([BENVA.%Burial_Data.NAM], [SDE_SPATIAL.GISADMIN.waugh_road_graves.GIS_Authority_Link]  ):  
  na = [BENVA.%Burial_Data.NAM]  
  if na is None
      na = [SDE_SPATIAL.GISADMIN.waugh_road_graves.GIS_Authority_Link]  
  return na.replace (",", "\n")
JoshuaBixby
MVP Esteemed Contributor

Since users have a bad habit of adding extra whitespace either before or after commas, I typically use a strategy of splitting, stripping, and rejoining the string so the stacked labels line up nicely.  Borrowing from Neil Ayres​'s example:

>>> na = "Fred ,Charlie, Neil"
>>> na
'Fred ,Charlie, Neil'
>>> print na.replace(",", "\n")
Fred
Charlie
 Neil
>>> print "\n".join(s.strip() for s in na.split(","))
Fred
Charlie
Neil
>>>
NeilAyres
MVP Frequent Contributor

Joshua,

much better.

BenVan_Kesteren1
Regular Contributor

Works beautifully, thanks for your assistance everyone

0 Kudos