简体   繁体   中英

Convert a string with curly brackets using python

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM