[GIS] cannot concatenate str and list objects

arcpygeoprocessingpython

I'm trying to rename a group of rasters to "I1986_" + [The 1st 3 letters of the raster]. For example, if a raster is named "Raster1", the output would be "I1986_Ras".

I've tried including str() functions in a couple places as well as .join in the tool's out data parameter but end up generating other errors. If I don't use rList variable in the Rename function and use the rasters variable instead, the script will rename the first file in the directory but then say i1986_xxx already exists. Any ideas?

arcpy.env.workspace = DIRECTORY
rList = arcpy.ListRasters()
for rasters in rList:
    arcpy.Rename_management(rList, "I1986_" + rList[0:3])

Best Answer

I believe you want something like below. rList is a list. It will concatenate with a string, but proabably not as you are expecting.

>>> l1 = ['cat','dog','mouse','monkey','elephant']
>>>'I1986_' + str(l1[0:3])
"I1986_['cat', 'dog', 'mouse']"

Python creates a string representation of the 1st 3 elements in the list. That is why the 1st iteration succeeds, but then the next fails and reports that the object already exists. This would rename all of your objects to the same name.

You're already looping through the list, so use your looping variable to concatenate with the elements of the list.

for raster in rList:
    newName = 'I1986_{}'.format(raster[0:3])
    arcpy.Rename_management(raster, newName)