How can str.translate from Python 2, only removing characters, be made to work in Python 3? [duplicate]

You are confusing the Python 2 str.translate() method with the Python 3 version (which is really the same as unicode.tranlate() in Python 2).

You can use the str.maketrans() static method to create a translation map; pass your string of digits to be removed in as the third argument to that function:

file_name.translate(str.maketrans('', '', '0123456789'))

Better still, store the result of str.maketrans() outside of the loop, and re-use it:

no_digits = str.maketrans('', '', '0123456789')

for file_name in file_list:
    os.rename(file_name, file_name.translate(no_digits))

Browse More Popular Posts

Leave a Comment