Rename object using for loop

Rename object using for loop

danispag
Enthusiast Enthusiast
1,889 Views
3 Replies
Message 1 of 4

Rename object using for loop

danispag
Enthusiast
Enthusiast

I have a list of objects which I want to rename. But I want each object to be renamed differently. Image attached as an example.

This is what I did so far but its not working as I want.

Can anyone help me please

Thanks in advance 🙂

 

lGrpSel = cmds.ls(leftFingers)

chunk_size = 3

leftChunks = [lGrpSel[i:i + chunk_size] for i in range(0, len(lGrpSel), chunk_size)]

 

side = 'left'
thumb = 'Thumb'
pointer = 'Pointer'
middle = 'Middle'
ring = 'Ring'
pinky = 'Pinky'
order = ['Base', '01', '02']
objType = 'CTRL'
spacer = '_'

for f in leftChunks:
for i in range(0, len(f), 1):
cmds.rename(f[i], side + thumb + spacer + order[i] + spacer + objType)
cmds.rename(f[i], side + pointer + spacer + order[i] + spacer + objType)
cmds.rename(f[i], side + middle + spacer + order[i] + spacer + objType)
cmds.rename(f[i], side + ring + spacer + order[i] + spacer + objType)
cmds.rename(f[i], side + pinky + spacer + order[i] + spacer + objType)

0 Likes
1,890 Views
3 Replies
Replies (3)
Message 2 of 4

lee.dunham
Collaborator
Collaborator

There are many, many ways in which you could achieve this - from almost hardcoded, to something potentially illegible, so I would say it would actually be a great learning exercise.

 

# Provide variables for grouped naming segments
side = 'left'
descriptors = [
    'Thumb',
    'Pointer',
    'Middle',
    'Ring',
    'Pinky',
]
identifiers = [
    '_base_CTRL',
    '_01_CTRL',
    '_02_CTRL',
]

# Get the selection and break it into groups of 3
selection = mc.ls(sl=True)
sel_chunk = [
    selection[i:i + 3]
    for i in range(0, len(selection), 3)
]

# Iterate the selection groups and descriptor for that group ('Thumb')
for sel_grp, desc in zip(sel_chunk, descriptors):

    # Iterate each item in the selection group along with an index
    for i, name in enumerate(sel_grp):

        # Construct the name. 
        # The modulus operator is very convenient (not to be confused with old-style string formatting).
        new_name = side + desc + identifiers[i % 3]

 

Python enumeration:

https://book.pythontips.com/en/latest/enumerate.html

 

Python modulus operator:

https://www.freecodecamp.org/news/the-python-modulo-operator-what-does-the-symbol-mean-in-python-sol...

 

 

There are many other ways to do this, but this seemed to closer to the direction you were heading.

 

0 Likes
Message 3 of 4

danielblaze
Contributor
Contributor

Amazing that worked perfectly :). Thank you so much

0 Likes
Message 4 of 4

lee.dunham
Collaborator
Collaborator

No problem

0 Likes