【问题标题】:Convert a string with curly brackets using python使用python转换带大括号的字符串
【发布时间】:2020-06-16 23:51:02
【问题描述】:

我有以下字符串:

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

如何在python中将任何类似的字符串转换为以下格式?

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

大括号中的数字应替换为相应的值。如果将值包装到{code{value}} 中,则应添加专用符号 ``。

【问题讨论】:

    标签: python regex parsing format


    【解决方案1】:

    好吧,这有点脆弱/混乱,但考虑到您提供的结构,它应该可以工作。

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

    返回:

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

    【讨论】:

    • 不错!谢谢!
    猜你喜欢
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多