0

I have two strings which contains the following substrings: myStringA and myStringBB; and a dictionary d which maps A and BB to some other values, lets say d["A"] = "X" and d["BB"] = "YY". I want to replace both of these strings by the following strings:

ThisIsMyStringX and ThisIsMyStringYY;. So that I want to replace A and BB (which are known for me) by the values from dictionary and leave ; if present at the end and add ThisIs and the beginning. How can I achieve that?

Jason
  • 313
  • 2
  • 8
  • 1
    Use `re.sub()` with a function as the replacement. The function can look up the match in the dictionary. – Barmar Sep 23 '22 at 23:39
  • Does this answer your question? "[Advanced string replacements in python](/q/26844742/90527)", "[Mass string replace in python?](/q/1919096/90527)" – outis Sep 25 '22 at 02:58

1 Answers1

1

You can use regex match-groups to achieve these replacements (a Match group is a Part of an regex encapsulated by brackets). For example:

import re

regex=re.compile("foo(bar)")
match = regex.match("foobar")
print(match.group(1))

will print "bar".
Here ist a working programm that solves your specific Problem:

import re

dict = {
   "A": "X",
   "BB": "YY"
}
myStringA = "myStringA"
myStringBB = "myStringBB"

regex = re.compile("my(\w+)(A|BB)")

match = regex.match(myStringA)
print("ThisIsMy"+ match.group(1) + 
dict[match.group(2)])

match = regex.match(myStringBB)
print("ThisIsMy"+ match.group(1) + 
dict[match.group(2)])
schlin
  • 117
  • 5