Python Strings and Methods for Autodesk Maya

Interactive examples to practice string manipulation techniques useful in Maya scripting

In Maya Python scripting, strings are essential for working with node names, file paths, commands, and more. This interactive guide lets you experiment with Python's string methods and see immediate results.

For each example, enter your own text in the input field and click the play button to see the result.

Basic String Operations

String Concatenation

Combines two or more strings together using the + operator. In Maya, this is often used to build command strings or create full paths.

Result:

Combined string: "sphere_01"
Python: str1 + str2

Maya usage example:

node_prefix = "pSphere"
node_number = "1"
full_node_name = node_prefix + node_number  # Creates "pSphere1"
cmds.select(full_node_name)

String Indexing

Access individual characters in a string using their index position (starting from 0). Useful for inspecting specific characters in node names.

Result:

Character at index 1: "C"
Python: str[1]

Maya usage example:

node_name = "pSphere1"
node_type = node_name[0]  # Gets 'p' which can indicate a polygon object
if node_type == "p":
    print("This is likely a polygon object")

String Slicing

Extract a substring using the slice notation [start:end]. Useful for extracting parts of object names or file paths in Maya.

Result:

Slice from index 0 to 9: "pCylinder"
Python: str[0:9]

Maya usage example:

file_path = "C:/Projects/Maya/scenes/character_rig_v001.mb"
file_name = file_path[-11:]  # Gets "v001.mb"
version_number = file_name[1:4]  # Gets "001"

Case Methods

.upper()

Converts all characters in a string to uppercase. Useful for case-insensitive comparisons in Maya scripts.

Result:

Uppercase: "LEFTARM_CTRL"
Python: str.upper()

Maya usage example:

user_input = "yes"
if user_input.upper() == "YES":
    # Process regardless of input case (yes, Yes, YES)
    cmds.polyCube(name="new_cube")

.lower()

Converts all characters in a string to lowercase. Useful for standardizing naming or case-insensitive comparisons.

Result:

Lowercase: "rightleg_grp"
Python: str.lower()

Maya usage example:

obj_name = "CHARACTER_RIG"
standardized_name = obj_name.lower()  # "character_rig"
cmds.rename(obj_name, standardized_name)

.title()

Converts the first character of each word to uppercase and the rest to lowercase. Useful for formatting display names in UIs.

Result:

Title case: "Character Facial Controls"
Python: str.title()

Maya usage example:

control_description = "head rotation controls"
display_name = control_description.title()  # "Head Rotation Controls"
cmds.button(label=display_name)

.capitalize()

Capitalizes the first character of the string and converts the rest to lowercase. Useful for formatting single labels or short descriptions.

Result:

Capitalized: "Maincontroller"
Python: str.capitalize()

Maya usage example:

error_message = "invalid selection"
formatted_message = error_message.capitalize()  # "Invalid selection"
cmds.warning(formatted_message)

Search Methods

.find()

Returns the index of the first occurrence of a substring, or -1 if not found. Useful for locating specific patterns in node names or paths.

Result:

Substring "arm" found at index 10.
Python: str.find("arm")

Maya usage example:

node_name = "character_arm_joint_01"
if node_name.find("arm") != -1:
    print("This is an arm joint")
    # Add arm-specific rigging code

.startswith()

Checks if a string starts with a specified prefix, returning True or False. Useful for filtering nodes by prefix naming conventions.

Result:

Does "jnt_spine_01" start with "jnt_"? true
Python: str.startswith("jnt_")

Maya usage example:

all_nodes = cmds.ls()
joint_nodes = []

for node in all_nodes:
    if node.startswith("jnt_"):
        joint_nodes.append(node)
        
print(f"Found {len(joint_nodes)} joints")

.endswith()

Checks if a string ends with a specified suffix, returning True or False. Useful for filtering nodes by suffix naming conventions.

Result:

Does "character_head_ctrl" end with "_ctrl"? true
Python: str.endswith("_ctrl")

Maya usage example:

all_objects = cmds.ls()
control_objects = []

for obj in all_objects:
    if obj.endswith("_ctrl"):
        control_objects.append(obj)
        
cmds.select(control_objects)  # Select all control objects

Modification Methods

.replace()

Replaces occurrences of a substring with another substring. Perfect for renaming parts of object names or updating file paths.

Result:

Result: "arm_right_ctrl"
Python: str.replace("left", "right")

Maya usage example:

left_nodes = cmds.ls("*left*")
for node in left_nodes:
    right_node_name = node.replace("left", "right")
    duplicate_node = cmds.duplicate(node, name=right_node_name)
    # Now mirror the duplicate to the right side

.strip()

Removes leading and trailing whitespace or specified characters. Useful for cleaning up user input or imported data.

Result:

Result: "pSphere1"
Python: str.strip()

Maya usage example:

user_input = "   pCube1   "  # User might add extra spaces
clean_input = user_input.strip()
if cmds.objExists(clean_input):
    cmds.select(clean_input)
else:
    cmds.warning("Object not found")

.split()

Splits a string into a list using a delimiter. Perfect for parsing paths, node hierarchies, or breaking down complex names.

Result:

Split into list: ["head_geo", "head_eyebrows_geo", "head_eyes_geo"]
Python: str.split("|")

Maya usage example:

full_path = "characters|hero|skeleton|spine|neck|head"
path_components = full_path.split("|")
parent_node = path_components[-2]  # "neck"
cmds.select(parent_node)

str.join()

Joins elements of an iterable with a specified string. Useful for building paths, constructing node names, or formatting output.

Result:

Joined string: "character_rig_arm_left_01"
Python: "_".join(["character", "rig", "arm", "left", "01"])

Maya usage example:

name_parts = ["character", "arm", "left", "ctrl"]
node_name = "_".join(name_parts)  # "character_arm_left_ctrl"
cmds.circle(name=node_name)

Maya-Specific Examples

Node Naming Convention Tool

Creates a Maya-style node name based on input parts. Demonstrates string concatenation and naming conventions.

Result:

Maya node name: "c_arm01_jnt"
Python: f"{prefix}{bodyPart}{str(index).zfill(2)}{type}"

Maya usage example:

def create_named_joint(side, part, index):
    side_prefix = {
        "left": "l_",
        "right": "r_",
        "center": "c_"
    }.get(side, "c_")
    
    node_name = f"{side_prefix}{part}{str(index).zfill(2)}_jnt"
    return cmds.joint(name=node_name)

# Create joints with proper naming
spine_joint = create_named_joint("center", "spine", 1)
left_arm_joint = create_named_joint("left", "arm", 1)

Maya File Path Manipulation

Extract and modify parts of a Maya file path. Demonstrates how to work with file paths in Maya scripts.

Result:

Directory: C:/Projects/Character/scenes Filename: character_model_v001.mb Base Name: character_model_v001 Extension: mb Clean Base: character_model Version: v001 Next Version: v002 Next Path: C:/Projects/Character/scenes/character_model_v002.mb # Python in Maya: directory = "C:/Projects/Character/scenes" filename = "character_model_v001.mb" basename = "character_model_v001" extension = "mb" clean_base = "character_model" version = "v001" next_version = "v002" next_path = "C:/Projects/Character/scenes/character_model_v002.mb"

Maya usage example:

def increment_version(file_path):
    # Split the path to get the directory and filename
    components = file_path.replace("\\", "/").split("/")
    directory = "/".join(components[:-1])
    file_name = components[-1]
    
    # Find version number
    if "_v" in file_name:
        base_name, version_ext = file_name.split("_v")
        version_num, ext = version_ext.split(".")
        
        # Increment version
        new_version = str(int(version_num) + 1).zfill(len(version_num))
        new_file_name = f"{base_name}_v{new_version}.{ext}"
        
        # Join to get new path
        new_path = f"{directory}/{new_file_name}"
        return new_path
    
    return file_path
    
current_path = cmds.file(q=True, sn=True)
new_path = increment_version(current_path)
cmds.file(rename=new_path)
cmds.file(save=True)

Made with DeepSite LogoDeepSite - 🧬 Remix