Reputation: 8487
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?
Upvotes: 2
Views: 186
Reputation: 15209
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
Upvotes: 3