2

I'd like to print something like the string below using Python:

{"_id":ObjectId("5a43ae09e2bae06ddd400dfc")}

At first I thought it would be easy, but it is not.

Here is my first attempt:

'{"_id":ObjectId("{}")}'.format('5a43ae09e2bae06ddd400dfc')

But I got the following error

Traceback (most recent call last): File "", line 1, in KeyError: '"_id"'

Then I tried:

'\{"_id":ObjectId("{}")\}'.format('5a43ae09e2bae06ddd400dfc')

And I got this error

Traceback (most recent call last): File "", line 1, in KeyError: '"_id"'

I managed to make it work with the following code:

'{"_id":ObjectId("%s")}' %('5a43ae09e2bae06ddd400dfc')
'{"_id":ObjectId("5a43ae09e2bae06ddd400dfc")}'

What's wrong with str format?

1 Answer 1

3

You need to escape your brackets so Python can tell the difference between a format parameter and a character that needs to be printed out, to do that you can just duplicate the brackets as follows:

print('{{"_id":ObjectId("{}")}}'.format('5a43ae09e2bae06ddd400dfc'))

Here is more info: https://docs.python.org/3/library/string.html#formatstrings

1
  • Thanks! but I still feel a bit strange, why not as common practice that use '\' to escape brackets
    – zhuguowei
    Dec 28, 2017 at 1:37

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.