Reputation: 305
I have string like
{'Y': [('A', 'X', datetime.datetime(2022, 3, 20, 22, 58, 30, 128000))]}
The end objective that I would like to get:
{'Y': [('A', 'X', 'datetime.datetime(2022, 3, 20, 22, 58, 30, 128000)')]}
I would like to add single quotes in the datetime.datetime(2022, 3, 20, 22, 58, 30, 128000). And in the string, this datetime.datetime(2022, 3, 20, 22, 58, 30, 128000) can multiple times.
What is the best to achieve this python?
Upvotes: 0
Views: 31
Reputation: 350821
If your input is indeed a string, and the only thing that may differ in the pattern you want to replace is the numbers that occur between parentheses, then you might want to use a regular expression to do the replacements:
import re
s = "{'Y': [('A', 'X', datetime.datetime(2022, 3, 20, 22, 58, 30, 128000))]}"
s = re.sub(r"\b((?<!['\"])datetime.datetime\([\s,\d]+\))", r"'\1'", s)
The downside is that if this pattern occurs also in encoded string literals, they will also get replaced, like here:
"{'Y': 'A X datetime.datetime(2022, 3, 20, 22, 58, 30, 128000) hello'}"
But if you find it unlikely to have such input, this might be the easiest solution.
Upvotes: 1