I want to sort the object numbers in order
The script below will rename all objects in the scene, so:

First having a base name before '.' is named from this base name (example &quot;Cube&quot;)
Next with the base name + their rank after the first one (example &quot;Cube.rank&quot;)

Comments below for key points:
import bpy


objects = bpy.context.scene.collection.all_objects

prev_base = &quot;&quot;
index = 0
sep = &quot;.&quot;

for name in sorted(o.name for o in objects):
    #Get the base name
    splitted = name.rsplit(sep, 1)
    base = splitted[0]
    #If the base name has changed
    if base != prev_base:
        #Keep a new base
        prev_base = base
        #Rename the object
        objects[name].name = base
        #Restart to 0
        index = 0
    else:
        #Next index
        index += 1
        #Assign formatted name
        objects[name].name = base + &quot;.&quot; + str(index).zfill(3)