Search code examples
pythonarcpycalculated-field

arcpy calculate string field: Any ideas what how to fix this?


Im trying to store a string value obtained from a loop through a tuple into a field called ROW_1

the code goes like this

for creekclass in listOfClassTuples:

                (classname, Permanency, creekWidth, score) = creekclass
                arcpy.AddMessage(int(score))

                bufferDistance = creekWidth*0.5
                if crossingType == "INTERSECT":
                    stringBuffer = ""
                else: 
                    stringBuffer = "%s Meters" % str(bufferDistance)
                    arcpy.AddMessage(str(bufferDistance))
                arcpy.MakeFeatureLayer_management(sourceLayer,"JUST_SELECTED", fieldName +" = '"+ classname + "'")
                #arcpy.SelectLayerByAttribute_management("JUST_SELECTED","NEW_SELECTION",fieldName+" = '"+ classname + "'")
                #arcpy.SelectLayerByAttribute_management("JUST_SELECTED","SUBSET_SELECTION",fieldName2+" = '"+ Permanency + "'")
                #arcpy.CopyFeatures_management("JUST_SELECTED", "A:\Temporary\TempLayer1.shp")                           
                arcpy.SelectLayerByLocation_management(targetLayer, crossingType,
                                                       "JUST_SELECTED", stringBuffer, "NEW_SELECTION")
               ## classname = classname.lower()

                if outputField1 != "":                                        

                            arcpy.CalculateField_management(targetLayer, outputField1, classname)
                            #arcpy.AddMessage(str(classname))

                            #arcpy.AddMessage(str(outputField1))

                arcpy.CalculateField_management(targetLayer, outputField2, int(score) )


                arcpy.Delete_management("Just_selected")
                arcpy.SelectLayerByAttribute_management(targetLayer, "CLEAR_SELECTION")

    except:

        arcpy.AddMessage("Function failed")
        arcpy.AddMessage(arcpy.GetMessages())

the problem appears when the variable classname is equal to "Virtual Flow":

classname = "Virtual Flow"

in the following line taken from the code above

if outputField1 != "":                                        

                            arcpy.CalculateField_management(targetLayer, outputField1, classname)

Solution

  • From the syntax in the esri help:

    CalculateField_management (in_table, field, expression, {expression_type}, {code_block})
    

    The third argument is a SQL Expression. Since you are passing a string that may have a space in it, the expression needs to be surrounded by single quotes ' '.

    Something like this should work:

    if outputField1 != "":                                        
    
                            arcpy.CalculateField_management(targetLayer, outputField1, "".join(("'",classname,"'"))