How can I print literal curly-brace characters in

2018-12-31 02:21发布

x = " \{ Hello \} {0} "
print x.format(42)

gives me : Key Error: Hello\\

I want to print the output: {Hello} 42

9条回答
与风俱净
2楼-- · 2018-12-31 02:51

You need to double the {{ and }}:

>>> x = " {{ Hello }} {0} "
>>> print x.format(42)
' { Hello } 42 '

Here's the relevant part of the Python documentation for format string syntax:

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

查看更多
忆尘夕之涩
3楼-- · 2018-12-31 02:56

Try this:

x = "{{ Hello }} {0}"

查看更多
泛滥B
4楼-- · 2018-12-31 03:01

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).

查看更多
登录 后发表回答