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

前端 未结 16 1459
面向向阳花
面向向阳花 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:38

    You escape it by doubling the braces.

    Eg:

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

    Although not any better, just for the reference, you can also do this:

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

    It can be useful for example when someone wants to print {argument}. It is maybe more readable than '{{{}}}'.format('argument')

    Note that you omit argument positions (e.g. {} instead of {0}) after Python 2.7

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

    Python 3.6+ (2017)

    In the recent versions of Python one would use f-strings (see also PEP498).

    With f-strings one should use double {{ or }}

    n = 42  
    print(f" {{Hello}} {n} ")
    

    produces the desired

     {Hello} 42
    

    If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:

    hello = "HELLO"
    print(f"{{{hello.lower()}}}")
    

    produces

    {hello}
    
    0 讨论(0)
  • 2020-11-21 05:39

    When you're just trying to interpolate code strings I'd suggest using jinja2 which is a full-featured template engine for Python, ie:

    from jinja2 import Template
    
    foo = Template('''
    #include <stdio.h>
    
    void main() {
        printf("hello universe number {{number}}");
    }
    ''')
    
    for i in range(2):
        print(foo.render(number=i))
    

    So you won't be enforced to duplicate curly braces as the whole bunch of other answers suggest

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

    Reason is , {} is the syntax of .format() so in your case .format() doesn't recognize {Hello} so it threw an error.

    you can override it by using double curly braces {{}},

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

    or

    try %s for text formatting,

    x = " { Hello } %s"
    print x%(42)  
    
    0 讨论(0)
  • 2020-11-21 05:46

    The OP wrote this comment:

    I was trying to format a small JSON for some purposes, like this: '{"all": false, "selected": "{}"}'.format(data) to get something like {"all": false, "selected": "1,2"}

    It's pretty common that the "escaping braces" issue comes up when dealing with JSON.

    I suggest doing this:

    import json
    data = "1,2"
    mydict = {"all": "false", "selected": data}
    json.dumps(mydict)
    

    It's cleaner than the alternative, which is:

    '{{"all": false, "selected": "{}"}}'.format(data)
    

    Using the json library is definitely preferable when the JSON string gets more complicated than the example.

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