Translate() Takes Exactly One Argument (2 Given)
I want to write a python program to rename all the files from a folder so that I remove the numbers from file name, for example: chicago65.jpg will be renamed as chicago.jpg. Below
Solution 1:
You are using the Python 2 str.translate()
signature in Python 3. There the method takes only 1 argument, a mapping from codepoints (integers) to a replacement or None
to delete that codepoint.
You can create a mapping with the str.maketrans()
static method instead:
os.rename(
file_temp,
file_temp.translate(str.maketrans('', '', '0123456789'))
)
Incidentally, that's also how the Python 2 unicode.translate()
works.
Solution 2:
If all you are looking to accomplish is to do the same thing you were doing in Python 2 in Python 3, here is what I was doing in Python 2.0 to throw away punctuation and numbers:
text = text.translate(None, string.punctuation)
text = text.translate(None, '1234567890')
Here is my Python 3.0 equivalent:
text = text.translate(str.maketrans('','',string.punctuation))
text = text.translate(str.maketrans('','','1234567890'))
Basically it says 'translate nothing to nothing' (first two parameters) and translate any punctuation or numbers to None (i.e. remove them).
Post a Comment for "Translate() Takes Exactly One Argument (2 Given)"