Cody Cody - 5 months ago 34
Python Question

What is the alternative to str.translate in python 3?

I am using the following function to remove numbers from filenames.

import os

def rename_files():
file_list = os.listdir(r"C:\Users\X\Downloads\Compressed\prank\prank")
## print(file_list)
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "1234567890"))


It works perfectly in python 2, but in python 3 it throws the following error.

Traceback (most recent call last):
File "C:\Python34\", line 11, in <module>
File "C:\Python34\", line 9, in rename_files
os.rename(file_name, file_name.translate(None, "1234567890"))
TypeError: translate() takes exactly one argument (2 given)

How to solve this problem without using regex.


str.translate still exists in Python 3, it's just used differently (though it matches unicode.translate from Py2). maketrans is now a static method of str (and bytes), and deletion of characters for str.maketrans is handled through the same lookup table use for translations.

For your case, one time up front you'd do:

deletedigits = str.maketrans(dict.fromkeys("1234567890"))

then perform the translation with:


Note that there are other ways to accomplish this, e.g.:

# ifilterfalse on Py2
''.join(itertools.filterfalse(str.isdigit, file_name))


''.join(let for let in file_name if not let.isdigit())