私信  •  关注

tvt173

tvt173 最近创建的主题
tvt173 最近回复了
7 年前
回复了 tvt173 创建的主题 » python:无法格式化类似json的字符串[duplicate]

def custom_format(string, brackets, *args, **kwargs):
    if len(brackets) != 2:
        raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
    padded = string.replace('{', '{{').replace('}', '}}')
    substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
    formatted = substituted.format(*args, **kwargs)
    return formatted

>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'

请注意,这既适用于长度为2的方括号,也适用于长度为2的iterable的两个字符串(用于多字符分隔符)。