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

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

Schitti
1#
Schitti Published in 2011-03-29 00:04:53Z
x = " \{ Hello \} {0} "
print x.format(42)

gives me : Key Error: Hello\\

I want to print the output: {Hello} 42

Greg Hewgill
2#
Greg Hewgill Reply to 2011-03-29 00:08:55Z

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

pajton
3#
pajton Reply to 2011-03-29 00:08:20Z

Try this:

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

Kamil Kisiel
4#
Kamil Kisiel Reply to 2014-03-28 06:34:23Z

You escape it by doubling the braces.

Eg:

x = "{{ Hello }} {0}"
print x.format(42)
DNR
5#
DNR Reply to 2011-03-29 00:08:31Z

Try doing this:

x = " {{ Hello }} {0} "
print x.format(42)
George Aprilis
6#
George Aprilis Reply to 2015-11-05 11:22:02Z

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

twasbrillig
7#
twasbrillig Reply to 2016-06-06 18:59:09Z

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.

tvt173
8#
tvt173 Reply to 2016-12-01 21:32:25Z

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

acacia
9#
acacia Reply to 2017-02-15 14:39:27Z

If you have to put braces around a value of a key of the parameter dictionaries or lists of the format method, try the following:

>>> "{o}Hello {a}{c}".format(**{"o":"{","c":"}","a":42})
'{Hello 42}'
Slim Shady
10#
Slim Shady Reply to 2017-06-19 17:11:45Z

Best solution for me is to use this '{ob} Hello {cb} 42'.format(ob='{',cb='}')

The reason why because good luck using accepted answer to print something like below.

a='Header'
ob = '{'
cb = '}' 


str = """
import {a} from '../actions/{a}';

class {a} {ob}
  constructor() {ob}
  {cb}
  somefuncSuccess(){ob}
    if(true){ob}{cb}
  {cb}
{cb}
"""
str = str.format(a=a,ob=ob, cb=cb)
print(str)

Output:

import Header from '../actions/Header';

    class Header {
      constructor() {
      }
      somefuncSuccess(){
         if(true){}
      }
    }
Mohideen ibn Mohammed
11#
Mohideen ibn Mohammed Reply to 2017-06-27 12:40:46Z

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)  
divenex
12#
divenex Reply to 2017-12-21 11:12:13Z

Python 3.6 (2017)

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

Also with f-strings one should use double {{ or }}

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

produces the desired

 {Hello} 42
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.34864 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO