[GIS] Loop through a list and concatenate a string in Arcpy

looppythonsql

I'm making a program where the user enters some codes (GetParameterAsText) that are going to be used in a SQL expression to select by atributes. I tried to find similar topics but didn't find a solution. This is part of a bigger program, but I'm going to show only the part with the issue.

ingresados = "10703,208,407"
splitIngresados = ingresados.split(",")
try:
    for i in splitIngresados:
        SQLexpresion = "PRM_IDENTIFICA LIKE '" + i + "%' OR"
        SQLexpresion += i
    print SQLexpresion
except:
    print "Se ha detectado un error que impide ejecutar el script"
    print (arcpy.GetMessage(2))

I need to get an expression that looks like this:

"PRM_IDENTIFICA LIKE '10703%' OR PRM_IDENTIFICA LIKE '208%' OR PRM_IDENTIFICA LIKE '407%'"

There is another thing. The user can enter multiple codes, I need a way to count them so I know when to end or close the SQL (So I don't write another "OR" in the end).

Best Answer

You can do this easily with string.join(iterable) and not even worry about when to close the sql statement

ingresados = "10703,208,407"
try:
    SQLexpression = "PRM_IDENTIFICA LIKE '" + "%' OR PRM_IDENTIFICA LIKE '".join(ingresados.split(",")) + "%'"
except:
    print "Se ha detectado un error que impide ejecutar el script"
    print (arcpy.GetMessage(2))

Here is a more readable version to get an idea of what is going on here.

ingresados = "10703,208,407"
splitIngresados = ingresadoes.split(",")
try:
    SQLexpression = "PRM_IDENTIFICA LIKE '"
    SQLexpression = SQLexpression + "%' OR PRM_IDENTIFICA LIKE '".join(splitIngresadoes)
    SQLexpression = SQLexpression + "%'"
except:
    print "Se ha detectado un error que impide ejecutar el script"
    print (arcpy.GetMessage(2))