0

Below is my code in ipython where I am adding a string value named "search_pattern" with a backslash to a dictionary. But when I print that dictionary back, it is replacing backslash with 2 backslashes. How can I add "search_pattern" to the dictionary as the original string.

In [91]: search_pattern = '"code":2[,}]|"vnew":"2/|"url":"(/o|/\.[^/]|/r=[^/])*/2[/"?]'

In [92]: test = {
    ...: "test" : search_pattern
    ...: }

In [93]: test
Out[93]: {'test': '"code":2[,}]|"vnew":"2/|"url":"(/o|/\\.[^/]|/r=[^/])*/2[/"?]'}

In [94]: print(test)
{'test': '"code":2[,}]|"vnew":"2/|"url":"(/o|/\\.[^/]|/r=[^/])*/2[/"?]'}

In [95]: type(test)
Out[95]: dict

Arjun
  • 545
  • 1
  • 6
  • 17
  • Does this answer your question? [How to get rid of double backslash in python windows file path string?](https://stackoverflow.com/questions/11924706/how-to-get-rid-of-double-backslash-in-python-windows-file-path-string) – Chris Doyle Jun 23 '20 at 13:00
  • Be sure to read the accepted answer in the link not just the title, the answer explains exactly whats happening in your code. Also have a look at your output of the string when you do `print(test["test"])` you will see that extra backslash isnt there really. – Chris Doyle Jun 23 '20 at 13:02
  • My scenario is, I am directly inserting this into a column in DB as json string. I can see that in DB, it is inserted with 2 slashes. I am using Python Django – Arjun Jun 23 '20 at 13:14
  • How are you serialising the data into the db? how are you forming the json? – Chris Doyle Jun 23 '20 at 13:18
  • I am forming the json same like I mentioned in the question and just pass it to a django table object. – Arjun Jun 23 '20 at 13:21
  • actually wait, json would also want the double backslash since backslash has special meaning in json. So i would expect it to keep the double backslash. If you put your json string from the db in a json validtor online it will say its valid, if you remove the extra double slash it will give you a parsing error. – Chris Doyle Jun 23 '20 at 13:24
  • But the problem here is even though I am having only one backslash while pushing to DB, python is appending 1 more. And while retrieving from DB, I am getting 2 backslashes. – Arjun Jun 23 '20 at 13:31
  • yes but when you convert it back from json string to python object that will again be stripped out. have a look at https://repl.it/repls/FloweryQuestionableUnderstanding – Chris Doyle Jun 23 '20 at 13:41

0 Answers0