littlejiver
littlejiver

Reputation: 255

how to replace all but the last instance of replace() in a string with python?

I'm trying to rename all the files in a director with this code (so far) however, I am not sure how to tell python not to replace the last instance of "."

I realize this is probably very simple but I am new to programming

any help would be appreciated !

import os

def main():

testDir = os.listdir("D:\TempServer\Videos\Series\American Dad\American 
Dad! S12 Season 12 [1080p WEB-DL HEVC x265 10bit] [AAC 5.1] [MKV] - ImE")
print(testDir)
newTestStr = ""


    for filename in testDir:
        testStr = "" + filename
        print(testStr.replace(".", " ", -1))

if __name__ == '__main__':
    main()

the "-1" isn't working and I am not sure what will

Upvotes: 0

Views: 381

Answers (3)

Taohidul Islam
Taohidul Islam

Reputation: 5414

Try this :

for filename in testDir:
        testStr = "" + filename
        total_occurances = filename.count('.')
        testStr = testStr.replace(".", " ", total_occurances-1)

Upvotes: 2

TigerhawkT3
TigerhawkT3

Reputation: 49330

str.replace takes the old substring, the new substring, and the count of how many times to perform the replacement. -1 is not a suitable value for the number of replacements. Count the number of times the old substring appears in the string, and then subtract one from that value and perform that number of replacements.

>>> s = 'abc x def x ghi x'
>>> val = s.count('x')
>>> s.replace('x', 'y', val-1)
'abc y def y ghi x'

Upvotes: 2

Thierry Lathuille
Thierry Lathuille

Reputation: 24279

Use os.splitext to separate the name and the extension, and join them after replacing the dots in the name:

for filename in testDir:
    name, ext = os.path.splitext(filename)
    name = name.replace('.', ' ')
    new_filename = name + ext
    print(new_filename)

Upvotes: 3

Related Questions