How can I print literal curly-brace characters in python string and also use .format on it?

前端 未结 16 1650
面向向阳花
面向向阳花 2020-11-21 05:31
x = \" \\{ Hello \\} {0} \"
print(x.format(42))

gives me : Key Error: Hello\\\\

I want to print the output: {Hello} 42

16条回答
  •  悲&欢浪女
    2020-11-21 06:02

    If you are going to be doing this a lot, it might be good to define a utility function that will let you use arbitrary brace substitutes instead, like

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

    Note that this will work either with brackets being a string of length 2 or an iterable of two strings (for multi-character delimiters).

提交回复
热议问题