Adding a suffix to an object name in Maya with Python
This one probably has quite limited use but nonetheless if there is 1 use then its good enough for me!
We are going to cover 2 things here, renaming an object AND using the .endswith() method to confirm that our renaming was successful.
We’ll do this within Maya so that we can see our object renamed in the outliner.
Create a new file in your
from maya import cmds
For the hell of it lets create a function which accepts the suffix so we can decide at execution what we want the suffix to be, rather than it being static in the code:
We could set the suffix to something default (like ‘_default’), but I want to introduce the raise command. Let’s add an ‘if’ statement to the function to check that we have provided a suffix argument, and if not we should raise an error:
def renameObj(suffix=None): if suffix == None: raise ValueError('No suffix specified')
We are checking if the suffix is equal to None, which it will be if we haven’t specified a value for suffix in the function call. Let’s test it out:
import ex_rename as exr
We should get the following output in the Maya console:
Error: ValueError: file /Users/johnplayer/Library/Preferences/Autodesk/maya/2018/scripts/ex_endswith.py line 9: No suffix specified #
This is what we were expecting and is great, not only are we catching a value error but we can give feedback as to what should be expected. We can now get on with writing our rename code.
Create our object
Now lets create an object:
# Create a cube cube = cmds.polyCube() # Store the name of object cubeshape = cube
We can now go straight in an rename the object, we have everything we need:
# Add the suffix to the object cmds.rename(cubeshape, cubeshape + suffix) # Update the variable name cubeshape = cubeshape + suffix
cmds= from the Maya commands library
.rename() = call the rename method
cubeshape = The existing name
cubeshape + suffix = The new name
That should do it! Lets run our code and this time include a suffix argument in the function call:
import ex_rename as exr
We have created an object, defined a suffix and applied the rename to the object, take a look at the outliner to confirm:
Confirming with .endswith()
Before we call this done, let’s try and get some confirmation out of the code. Rather than checking the object name in its entirety, we can confirm that the object ‘ends with’ our suffix:
# Check if the new suffix has been applied if cubeshape.endswith(suffix): print 'Yep!'