I want to replace /
with a \/
in a string. For an example
original_string="https://stackoverflow.com/questions/"
modified_string="https:\/\/stackoverflow.com\/questions\/"
modified_string
is the required output. I tried the following and neither of them seems to be working.
modified_string=original_string.replace('/','\/')
modified_string=original_string.replace('/',r'\/')
modified_string=re.sub("/", r"\/", original_string)
They provide the following output when saving it to a file,
modified_string="https:\\/\\/stackoverflow.com\\/questions\\/"
print(modified_string)
outputs the correct string ignoring the escape character, but how can we keep the same output when saving it to a file. Is there a way to disable escape characters in python and treat it as just a character?
***A Complete Sample code is added below to regenerate the problem ***
original_string="https://stackoverflow.com/questions/"
modified_string=original_string.replace('/','\/')
#url.json file contains the following
#{"website":{"title":"stackoverflow","url":"https:\/\/www.google.com\/"}}
import json
f = open('url.json')
data = json.load(f)
f.close()
data["website"]["url"]=modified_string
with open("url.json", "w") as outfile:
json.dump(data, outfile)
#Output file comes as the following which is not the expected output
# {"website": {"title": "stackoverflow", "url": "https:\\/\\/stackoverflow.com\\/questions\\/"}}