Python - Script to Assign Materials based on Mesh Name

hoping someone may be able to help out with a script to automatically assign materials to meshes based on their names. I've not had any Python experience so it's all a bit beyond me.

I'm importing a series of car models (FBXs each consisting of around 25 mesh objects) into a scene to render (Cycles) and need to apply materials to the selected meshes (ideally more than one at once). The materials have already been created in the scene and applied to temp meshes (moved to layer 2). Each mesh object from the imported FBX has been named to match the material that needs to be applied (eg. "Car_Tyres" mesh needs "Car_Tyres" material applied).

Can someone help me out with a script or point me in the direction of a solution, I've had no luck searching previous questions on here. Thanks heaps for your time :)

Please try running this and let me know if there are any errors: (I just hope I understand your requirement correctly :)

import bpy

for obj in bpy.data.objects:
objName = obj.name
mat = bpy.data.materials.get(objName)
if(mat != None):
if(mat.name not in obj.data.materials):
obj.data.materials.append(mat)
obj.active_material_index = len(obj.data.materials)-1
else:
obj.active_material_index =  [*obj.data.materials].index(mat)
else:
print('No material available for', objName)

• Thanks so much @BlenderDadaist, that works perfectly! I found I had to remove the default materials that the FBX imported with first (via another script), then your script applied the materials just as I'd hoped, thanks again, you've saved me a few thousand clicks! :) – SQUIDS Sep 19 '18 at 8:58
• You are welcome :) – Blender Dadaist Sep 19 '18 at 10:24