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?

2

1 Answer 1

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)])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.