![]() |
Substitue multiple substrings in one command - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Substitue multiple substrings in one command (/thread-37760.html) |
Substitue multiple substrings in one command - Pavel_47 - Jul-18-2022 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)
|