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?

0

4 Answers 4

11

You just need one more pair of {}

'This string is {{{}}}'.format('wonderful')
Sign up to request clarification or add additional context in comments.

2 Comments

Superb, it looks ridiculous, but it works :)
@Jonathan Yeah, I wish it was \{.
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'))

4 Comments

I think they were revoked because you added the explanation.
@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).
@vaultah thanks. interesting meta-post!
1

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

'This string is {{{}}}'.format('wonderful')

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.