Python Forum
Substitue multiple substrings in one command
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Substitue multiple substrings in one command
#1
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 >>>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Find string between two substrings, in a stream of data xbit 1 2,144 May-09-2021, 03:32 PM
Last Post: bowlofred
  Using lambdas and map() to parse substrings in a single line Drone4four 5 3,050 Sep-20-2020, 10:38 AM
Last Post: snippsat
  Taking Multiple Command Line Argument Input bwdu 6 4,023 Mar-29-2020, 05:52 PM
Last Post: buran
  substring between substrings Skaperen 5 4,135 Oct-27-2018, 08:45 PM
Last Post: ichabod801
  multiple values as parameters to POST command.. onenessboy 17 14,743 Feb-25-2018, 09:57 AM
Last Post: onenessboy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020