在问这个问题时,我意识到我对原始字符串知之甚少.对于那些自称是Django训练师的人来说,这很糟糕.
我知道编码是什么,而且我知道u''自从我得到什么是Unicode以来我们独自做了什么.
但到底r''做了什么呢?它会产生什么样的字符串?
And above all, what the heck does ur'' do?
Finally, is there any reliable way to go back from a Unicode string to a simple raw string?
Ah, and by the way, if your system and your text editor charset are set to UTF-8, does u'' actually do anything?
当我创建一个包含反斜杠的字符串时,它们会重复:
>>> my_string = "why\does\it\happen?"
>>> my_string
'why\\does\\it\\happen?'
Run Code Online (Sandbox Code Playgroud)
为什么?
由于正斜杠只能出现在JSON序列化对象内的字符串中,因此不会使用转义(在默认设置中)
json.dump(some_dict).replace('/', r'\/')
Run Code Online (Sandbox Code Playgroud)
可靠的工作,但它看起来很hacky.
我知道正向斜线不必逃脱,但你可以逃脱它们,对于我的用例,我想让它们逃脱.
有没有办法让JSONEncoder在不手动转义它们的情况下转义正斜杠?
python ×3
escaping ×2
json ×2
backslash ×1
javascript ×1
python-2.7 ×1
python-2.x ×1
rawstring ×1
repr ×1
string ×1
unicode ×1