Cody Cody - 22 days ago 10
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)
os.chdir(r"C:\Users\X\Downloads\Compressed\prank\prank")
print(os.getcwd())
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "1234567890"))

rename_files()


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

Traceback (most recent call last):
File "C:\Python34\rename_files.py", line 11, in <module>
rename_files()
File "C:\Python34\rename_files.py", 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.

Answer

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:

file_name.translate(deletedigits)

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

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

or:

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