Change string structure to another
Question:
I have the following given pattern and expected pattern:
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 I was wondering if there are other solutions, or libraries that can help.
Answers:
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
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(" < "))
I have the following given pattern and expected pattern:
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 I was wondering if there are other solutions, or libraries that can help.
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
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(" < "))