0

I have the following string:

{At condition {0}, the value of {1} must be between {2} and {3}.}{{code{min <= 100}}}{{code{min}}}{0}{100}

How to convert any similar string to the below format in python?

At condition `min <= 100`, the value of `min` must be between 0 and 100.

Numbers in curly brackets should be replaced by the corresponding values. If a value is wrapped into {code{value}}, dedicated symbols `` should be added.

1 Answer 1

1

Alright this is a little brittle/messy but it should work given the structure you provided.

def convert(s):
    # Find index  of first }{ as this is end of initial string
    idx = s.find('}{')
    initial = s[1:idx]
    # Everything after this index is an argument
    args = s[idx+2:-1]
    args = args.split('}{')
    # Iterate through args and subsitute into initial string
    for i, arg in enumerate(args):
        # Check to see if arg wrapped in {code{}}
        val_idx = arg.find('code{')
        if val_idx != -1:
            # Replace wrapped value with backticks
            arg = '`{}`'.format(arg[val_idx+5:-2])
        # Place arg into proper place in initial string
        initial = initial.replace('{{{}}}'.format(i), arg)

    return initial

Calling:

convert('{At condition {0}, the value of {1} must be between {2} and {3}.}{{code{min <= 100}}}{{code{min}}}{0}{100}')
convert('{{0} bar}{foo}')

Returns:

At condition `min <= 100`, the value of `min` must be between 0 and 100.
foo bar
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.