Select to view content in your preferred language

concatenate where one field may be null

961
2
10-18-2011 07:46 AM
PeterHoffman
Deactivated User
I am trying to run this script and where I am conactenating a first name and a lastname with a space inbetween. What is happening is that if the first name is null I get a blank space in front for the owner name. I am using a file geodatabase.
I have left out the other code that is not needed for this exaple.

Here is my code that runs w/o error but puts a space in front for null firstname.

RPT_PARCELS_OWNER_DATA_with_OwnerName_Field = "C:\\Application Database\\RPTSA.gdb\\RPT_PARCELS_OWNER_DATA"

gp.CalculateField_management(RPT_PARCELS_OWNER_DATA_with_OwnerName_Field, "OwnerName", "[FIRST_NAME] +\" \"+ [LAST_NAME]", "VB", "")

I have tried an expression and a codeblock but I get error message.

Here is my try:

expression = 'concat(!FIRST_NAME!,!LAST_NAME!)'
codeBlock = \
    "def concat(first,last):\
    if first == '':\
    return !LAST_NAME!\
    else:\
    return !FIRST_NAME! + ' ' + !LAST_NAME!"

gp.CalculateField_management(RPT_PARCELS_OWNER_DATA_with_OwnerName_Field, "OwnerName", expression, "PYTHON", codeBlock)
 
The error message says the parameters are not valid.
Thanks for help, I am a novice at python.
Tags (2)
0 Kudos
2 Replies
DarrenWiens2
MVP Alum
"def concat(first,last):\
if first == '':\
return !LAST_NAME!\
else:\
return !FIRST_NAME! + ' ' + !LAST_NAME!"


You've passed the values of FIRST_NAME and LAST_NAME into variables called first and last. Also, I'm pretty sure you need to maintain proper Python indentation. So:
"def concat(first,last):\
    if first == '':\
        return last\
    else:\
        return first + ' ' + last"
 
0 Kudos
PeterHoffman
Deactivated User
I sent a interim version, I had changed the variables as you suggested.

Anyhow, I found some better examples and came up with this which works:

expression = "concatname(str(!FIRST_NAME!),str(!LAST_NAME!))"
def concatname(first,last):
first = first.strip()
retval = first + ' ' + last
return retval.strip()

gp.CalculateField_management(RPT_PARCELS_OWNER_DATA_with_OwnerName_Field, "OwnerName", expression, "PYTHON")
0 Kudos