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.

Asked By: User 19826

||

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
Answered By: Tim Biegeleisen

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

Answered By: blhsing
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.