1 year ago

#286085

test-img

PythonKiddieScripterX

Force odd number of backslashes in dictionary

I am specifically looking to print this in the terminal {'Name': '[{\\\"test\\\\":\\\"somedata\\\"}]'}

So far I can get 2 slashes or 4 slashes but I am not sure how to three slashes.

I tried doing replace('"','\\\"')

fdsa = {"Name":'[{"test":"somedata"}]'}
fdsa["Name"] = fdsa["Name"].replace('"','\\\"')
print(fdsa)
#{'Name': '[{\\"test\\":\\"somedata\\"}]'}

I tried doing replace('"','\\\\"')

fdsa = {"Name":'[{"test":"somedata"}]'}
fdsa["Name"] = fdsa["Name"].replace('"','\\\\"')
print(fdsa)
#{'Name': '[{\\\\"test\\\\":\\\\"somedata\\\\"}]'}

I tried doing replace('"',r'\"')

fdsa = {"Name":'[{"test":"somedata"}]'}
fdsa["Name"] = fdsa["Name"].replace('"',r'\"')
print(fdsa)
#{'Name': '[{\\"test\\":\\"somedata\\"}]'}

I tried doing replace('"',r'\"')

fdsa = {"Name":'[{"test":"somedata"}]'}
fdsa["Name"] = fdsa["Name"].replace('"',r'\\"')
print(fdsa)
#{'Name': '[{\\\\"test\\\\":\\\\"somedata\\\\"}]'}

I googled as much as I could and came to the conclusion that raw strings can't have an odd number of backslashes https://note.nkmk.me/en/python-raw-string-escape/#:~:text=source%3A%20raw_string_escape.py-,Raw%20strings%20cannot%20end%20with%20an%20odd%20number%20of%20backslashes,the%20end%20of%20the%20string.

but I am not sure if there is a work around for this?

https://stackoverflow.com/a/22792332

Odd or even number of backslashes and escaped character

edit: I tried using unicode as @TDG mention but it still came out as 3 slashes

backslash = '\u005c' 
fdsa = {"Name":'[{"test":"somedata"}]'}
fdsa["Name"] = fdsa["Name"].replace('"',f'{backslash*3}'+'"')
print(fdsa)

python

string

dictionary

backslash

0 Answers

Your Answer

Accepted video resources