i'm stumped... i get strange results from string[10:] to get the last 10 characters from a string?

the code supposed to rename a batch of file sequentially and the number of numbers needs to be consistent eg. 00001 - 99999

thanks for the help

import os

x=0
for file in os.listdir("/path"):
    newname = "0000000000" + str(x) + ".dpx"

    newname = "/path/koons_" + newname[10:]

    (basename, extention) = os.path.splitext(file)
    oldname = "/path/" + file
    if extention== ".dpx":
        x = x+1
        print newname
        print oldname
        #os.rename(file, newname)

The syntax is str[from:to]. So typing string[10:] will return a string containing all characters beginning from the 10th character of your original string.
To get the last 10 characters from a string you should type string[(len(string) - 10):].
A smarter way of doing it would be string[:-10].
The negative index tell the interpreter to count from the end of the string.

For example :

>>> string = 'this is a test string'
>>> string[:-10]
'est string'
>>>

Incorrect:

>> string = 'this is a test string'
>>> string[:-10]
'this is a t'
>>> ## right way
>>> string[-10:]
'est string'
>>>

my problem was perception... on mac terminal, i typed clear, instead of cmd+k, so when i scrolled back i kept seeing my first mistaken attempt. thanks working perfectly now that my head screwed on!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.