使用python转换带花括号的字符串

使用python转换带花括号的字符串,python,regex,parsing,format,Python,Regex,Parsing,Format,我有以下字符串: {At condition {0}, the value of {1} must be between {2} and {3}.}{{code{min <= 100}}}{{code{min}}}{0}{100} {在条件{0}下,{1}的值必须在{2}和{3}之间。{code{min好的,这有点脆弱/混乱,但考虑到您提供的结构,它应该可以工作 def convert(s): # Find index of first }{ as this is end of

我有以下字符串:

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

{在条件{0}下,{1}的值必须在{2}和{3}之间。{code{min好的,这有点脆弱/混乱,但考虑到您提供的结构,它应该可以工作

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
电话:

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}')

convert({At condition{0},{1}的值必须在{2}和{3}之间。}{code{min Nice!谢谢!
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}')
At condition `min <= 100`, the value of `min` must be between 0 and 100.
foo bar