简体   繁体   English

如何将正确的转义序列字符添加到字符串中

[英]How to add a proper escape sequence character into string

I have defined variable 'a' with a value of a dictionary as a string.我已经定义了变量 'a' ,它的值是一个字典作为字符串。 Got an error when trying to load that string as json.尝试将该字符串加载为 json 时出错。

>>> a = '{"key":"^~\\&"}'
>>> data = json.loads(a, object_pairs_hook=OrderedDict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 352, in loads
    return cls(encoding=encoding, **kw).decode(s)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 380, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Invalid \escape: line 1 column 9 (char 8)
>>> 

Is there a way to make this happen有没有办法做到这一点

using raw strings avoids that python "eats" one backslash, and then loading works:使用原始字符串可以避免 python “吃掉”一个反斜杠,然后加载工作:

>>> a = r'{"key":"^~\\&"}'
>>> print(json.loads(a))
{'key': '^~\\&'}

the backslash is still doubled because of the representation of the string but here:由于字符串的表示,反斜杠仍然加倍,但在这里:

>>> print(json.loads(a)["key"])
^~\&

it works fine它工作正常

Of course, if your data already contains the string in question, raw strings won't help.当然,如果您的数据已经包含相关字符串,原始字符串将无济于事。 In that case use replace :在这种情况下使用replace

>>> a = '{"key":"^~\\&"}'  # wrong
>>> a = a.replace("\\","\\\\")
>>> print(json.dumps(json.loads(a)))
{"key": "^~\\&"}

works too.也有效。

When dealing with strings which include backslashes you should always use raw string literals:在处理包含反斜杠的字符串时,您应该始终使用原始字符串文字:
(just put r before the string) (只需将r放在字符串之前)

>>> a = r'{"key":"^~\\&"}'
>>> data = json.loads(a, object_pairs_hook=OrderedDict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM