1

I have a str as follows:

str = "ObjectId('60fe547ce9d9f9fd5f03bdab')"

I want to convert it to bson.objectid. Since the ObjectId() function only requires the 24 digit hex string so I am achieving this with string manipulation which is definitely not the right way:

obj = ObjectId(str[10:34])

Is there a standard way or any better way to achieve this.

Edit: I receive the string data in an HTTP POST request

Ammar H Sufyan
  • 97
  • 1
  • 3
  • 13

2 Answers2

0

This looks like a good way to achieve what you need. Sometimes the best way of doing things is the simplest. If you are worried that the number of characters in objectID changes, I would use re.sub and look for '(' and ')' Find and remove a string starting and ending with a specific substring in python

joey
  • 115
  • 8
0

Your answer seems fine. You can also use eval and exec as explained here, but it has more cons than your answer.

4 3 2
  • 43
  • 6