I have a number of given patterns and expected patterns, one example is below:
given_str = "A < B < C"
expected_str = "A[B] = C"
so if I am a given a string which is similar to given_str I need to change it to expected_str and return it.
Suppose I am given the string:
str1= "aaa < bbb < ccc"
I have written the following code to generate the expected string which is str2:
p1 = str1.split("<")
v1=p1[0]
v2=p1[1]
v3=p1[-1]
str2 = v1 "[" v2 "]" v3
The above works, but it is not a good solution as I have many differnt given and expected patterns, and writing a seperate module that splits a string and builds a new one depending on the expected output is going to take a excessive amount of time.
I was wondering if there are other solutions, or libraries that can help.
CodePudding user response:
You could use a regex replacement here:
str1 = "aaa < bbb < ccc"
output = re.sub(r'(\w ) < (\w ) < (\w )', r'\1[\2] = \3', str1)
print(output) # aaa[bbb] = ccc
CodePudding user response:
You can split the string with " < "
and unpack the resulting list to the str.format
method to reformat it:
str1 = "A < B < C"
str2 = "{}[{}] = {}".format(*str1.split(" < "))
Demo: https://replit.com/@blhsing/FrighteningMisguidedLists
CodePudding user response:
Given two strings A and B, the task is to convert A to B if possible. The only operation allowed is to put any character from A and insert it at front. Find if it’s possible to convert the string. If yes, then output minimum no. of operations required for transformation.