Comment faire un equivalent de str_replace() de php en python
La fonction strReplace
1 2 3 4 5 6 7 8 | import os import string import shutil def strReplace(str, array): for search, replace in array: str = str.replace(search, replace) return str |
Utilisation
replace = [(' ', '_'), ('-', '')] for dir in os.listdir('.'): newdir = strReplace(dir, replace).capitalize() print ("moving: %s > %s"% (dir, newdir)) os.rename(dir, newdir)
ce qui nous donne dans ce cas précis
moving: Angel of Retribution > Angel_of_retribution moving: Living After Midnight > Living_after_midnight moving: British Steel > British_steel moving: Defenders Of The Faith > Defenders_of_the_faith moving: Killing Machine > Killing_machine moving: Ram It Down > Ram_it_down moving: Hell Bent For Leather > Hell_bent_for_leather moving: Stained Class > Stained_class moving: Sin After Sin > Sin_after_sin moving: Jugulator > Jugulator moving: Screaming For Vengeance > Screaming_for_vengeance moving: Turbo > Turbo moving: Painkiller > Painkiller moving: Rocka Rolla > Rocka_rolla moving: Point Of Entry > Point_of_entry moving: Demolition > Demolition moving: Priest...Live! > Priest...live! moving: Sad Wings Of Destiny > Sad_wings_of_destiny