Python Forum

Full Version: Substitue multiple substrings in one command
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I have been looking for a solution to replace several different string fragments with different other fragments.
Here's a solution I found, which seems a bit cumbersome.
There may be other solutions.

import re
str1 = ''.join(('France, ', 'Etats-Unis, ', 'Belgique, ', 'Portugal, ',
               'Espagne, ', 'Allemagne, ', 'Canada, ', 'Hong Kong, ',
               'Royaume-Uni, ', 'Inde, ', 'Norvège, ', 'Israël, ', 'Australie, ',
               'Japon, ', 'République tchèque, ', 'Pologne, ', 'Suisse, ', 'Indonésie'))
print(str1)
rep = {"France": "FRA", "Etats-Unis": "USA", "Royaume-Uni": "GB", "République tchèque": "Rep. Tch."}
rep = dict((re.escape(k), v) for k, v in rep.items())
pattern = re.compile("|".join(rep.keys()))
str1 = pattern.sub(lambda m: rep[re.escape(m.group(0))], str1)
print(str1)
Output:
>>> ====== RESTART: /home/pavel/python_code/replace_multiple_substrings.py ====== France, Etats-Unis, Belgique, Portugal, Espagne, Allemagne, Canada, Hong Kong, Royaume-Uni, Inde, Norvège, Israël, Australie, Japon, République tchèque, Pologne, Suisse, Indonésie FRA, USA, Belgique, Portugal, Espagne, Allemagne, Canada, Hong Kong, GB, Inde, Norvège, Israël, Australie, Japon, Rep. Tch., Pologne, Suisse, Indonésie >>>