Select to view content in your preferred language

Python issue in field calculator with quotes and apostrophes.

889
2
07-19-2011 08:43 AM
JamesDewar
New Contributor
I am stumped on this problem.  I am using the field calculator codeblock interface within model builder to automate some tasks.  As part of that, I have a simple if then statement that I use to remove any null or blank values from the select string fields.  The problem I am having is that if there are any double quotes AND apostrophes within the strings, the code will no work.  For example, the code below will work if there are apostrohes in the field strings, but not if there are double quotes.   

Expression: Reclass(str(!COM_NAME!))
Code block:
def Reclass(COM_NAME):
if COM_NAME == "" or COM_NAME == " ":
    return "[No Value Listed]"
else:
    return COM_NAME

On the other hand,  if I change the expression to Reclass(str('!COM_NAME!')), it will work with double quotes but not apostrophes.  VBS can get around this issue easily, but I am just curious if there is a simple work around in python as well.
Tags (2)
0 Kudos
2 Replies
ChristopherFricke1
Deactivated User
Not sure if this will work, but worth a shot.

Wrap three quotes around your return value.


return """COM_NAME"""
[\CODE]
0 Kudos
StacyRendall1
Frequent Contributor
Hey, as you are just looking for empty strings, try this instead:

Expression: Reclass(str(!COM_NAME!))
Code block:
def Reclass(COM_NAME):
    if (len(COM_NAME) == 0) or (COM_NAME.isspace()):
        return "[No Value Listed]"
    else:
        return COM_NAME 


If a string is just '', its length is zero, while if it contains only spaces the .isspace() tool will return True.

I just tried this on a few things with different quotes in them (just in Python); they worked fine. If your calculator still has a problem it may be that Arc does not like the strings with the quotes in them...?
0 Kudos