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

前端 未结 16 1629
面向向阳花
面向向阳花 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 05:46

    If you want to only print one curly brace (for example {) you can use {{, and you can add more braces later in the string if you want. For example:

    >>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
    '{ there is a curly brace on the left. Oh, and 1 + 1 is 2'
    
    0 讨论(0)
  • 2020-11-21 05:47

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

    0 讨论(0)
  • 2020-11-21 05:47

    You can do this by using raw string method by simply adding character 'r' without quotes before the string.

    # to print '{I am inside braces}'
    print(r'{I am inside braces}')
    
    0 讨论(0)
  • 2020-11-21 05:49

    Try doing this:

    x = " {{ Hello }} {0} "
    print x.format(42)
    
    0 讨论(0)
  • 2020-11-21 05:51

    Use escape sequences to escape the curly braces in the f-string. Ex:print(f'{a={1}}')

    0 讨论(0)
  • 2020-11-21 05:55

    I recently ran into this, because I wanted to inject strings into preformatted JSON. My solution was to create a helper method, like this:

    def preformat(msg):
        """ allow {{key}} to be used for formatting in text
        that already uses curly braces.  First switch this into
        something else, replace curlies with double curlies, and then
        switch back to regular braces
        """
        msg = msg.replace('{{', '<<<').replace('}}', '>>>')
        msg = msg.replace('{', '{{').replace('}', '}}')
        msg = msg.replace('<<<', '{').replace('>>>', '}')
        return msg
    

    You can then do something like:

    formatted = preformat("""
        {
            "foo": "{{bar}}"
        }""").format(bar="gas")
    

    Gets the job done if performance is not an issue.

    0 讨论(0)
提交回复
热议问题