7

Ponder that you have a string which looks like the following 'This string is {{}}' and you would like to transform it into the following 'This string is {wonderful}'

if you do 'This string is {{}}'.format('wonderful') it won't work. What's the best way to achieve this?

Jonathan
  • 8,453
  • 9
  • 51
  • 74

4 Answers4

10

You just need one more pair of {}

'This string is {{{}}}'.format('wonderful')
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
3

you need triple brackets: two for the literal { and }and the pair in the middle for the format function.

print('This string is {{{}}}'.format('wonderful'))
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • I think they were revoked because you added the explanation. – vaultah Oct 22 '15 at 16:54
  • @vaultah that's kind of the MO for questions a simple as that. everyone posts code as fast as possible and then adds an explanation later. ninja-editing... i did so as well... (and had to answer a captcha). – hiro protagonist Oct 22 '15 at 16:56
  • ["You are welcome to post a first version of your answer as fast as you can, provided it is already a correct and useful answer meeting our minimal standards."](http://meta.stackoverflow.com/a/303449/2301450) – vaultah Oct 22 '15 at 16:58
  • @vaultah thanks. interesting meta-post! – hiro protagonist Oct 22 '15 at 16:59
1

Two brackets to get {} in line (escaping), and third as placeholder:

'This string is {{{}}}'.format('wonderful')
Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
-2

You can do this: print "{{f}}".format(f='wonderful').

You can do this as well: "Hello, {name}!".format(name='John'). This will substitute all {name}s with John.

ForceBru
  • 43,482
  • 10
  • 63
  • 98