[GIS] Reserved Ampersand Character in Label Expression of ArcGIS for Desktop

arcgis-10.3arcgis-desktoplabelingpython

I have this code which works…

def FindLabel ([NUMBERNAME], [NUMBER], [BLOCK], [SURNUM]):
      lineone = "A:"+ [NUMBER]
      absName = "<CLR red='255'><FNT size = '14'>" + [NUMBERNAME] + "</FNT></CLR>"
      if [NUMBERNAME] is not None:
          return lineone + '\n' + absName + '\n' + "BLK:" + [BLOCK] + '\n' + "SEC:"+ [SURNUM] 

However I have some field values in [NUMBERNAME] that contain the reserved ampersand character (&). If the value contains the ampersand character the label looks like this…

<CLR red='255'><FNT size = '5.5'>T&P RR CO</FNT></CLR>
BLK: 
SEC: 

Versus (in this example) a label that looks like…

'T&P RR CO'

I have found this documentation, which references this code to fix the ampersand issue….

 Function FindLabel ([LABELFIELD])
  NewString = Replace([LABELFIELD],"&","&amp;")  
  FindLabel = "<ITA>" & NewString & "</ITA>"
End Function

This is in VBScript. How would I do something similar to this using the Python parser of ArcGIS 10.3 for Desktop?

Best Answer

Python has a similar replace method you can use:

def FindLabel ([NUMBERNAME], [NUMBER], [BLOCK], [SURNUM]):
      lineone = "A:" + [NUMBER]
      numName = [NUMBERNAME].replace("&", "&amp;")
      absName = "<CLR red='255'><FNT size = '14'>" + numName + "</FNT></CLR>"
      if [NUMBERNAME] is not None:
          return lineone + '\n' + absName + '\n' + "BLK:" + [BLOCK] + '\n' + "SEC:"+ [SURNUM]