string - translate() takes exactly one argument (2 given) in python error -


import os import re  def rename_files():     # files dir     file_list=os.listdir(r"c:\oop\prank")     print(file_list)     saved_path=os.getcwd()     print("current working directory"+saved_path)     os.chdir(r"c:\oop\prank")     #rename files     file_name in file_list:         print("old name-"+file_name)         #print("new name-"+file_name.strip("0123456789"))         os.rename(file_name,file_name.translate(none,"0123456789"))         os.chdir(saved_path)  rename_files() 

here error showing due translate line ...help me next ..i using translate remove digit filename.

traceback (most recent call last):     file "c:\users\vikash\appdata\local\programs\python\python35-  32\pythonprogram\secretname.py", line 17, in <module> rename_files()       file "c:\users\vikash\appdata\local\programs\python\python35-  32\pythonprogram\secretname.py", line 15, in rename_files      os.rename(file_name,file_name.translate(none,"0123456789"))      typeerror: translate() takes 1 argument (2 given) 

str.translate requires dict maps unicode ordinals other unicode oridinals (or none if want remove character). can create so:

old_string = "file52.txt" to_remove = "0123456789" table = {ord(char): none char in to_remove} new_string = old_string.translate(table) assert new_string == "file.txt" 

however, there simpler way of making table though, using str.maketrans function. can take variety of arguments, want 3 arg form. ignore first 2 args mapping characters other characters. third arg characters wish remove.

old_string = "file52.txt" to_remove = "0123456789" table = str.maketrans("", "", to_remove) new_string = old_string.translate(table) assert new_string == "file.txt" 

Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -