Python"string_escape"vs"unicode_escape"

Mik*_*ers 26 python quotes encoding escaping

根据文档,内置字符串编码string_escape:

在Python源代码中生成一个适合作为字符串文字的字符串

......而unicode_escape:

在Python源代码中生成一个适合作为Unicode文字的字符串

所以,他们应该有大致相同的行为.但是,他们似乎对待单引号的方式不同:

>>> print """before '" \0 after""".encode('string-escape')
before \'" \x00 after
>>> print """before '" \0 after""".encode('unicode-escape')
before '" \x00 after
Run Code Online (Sandbox Code Playgroud)

string_escape单引号的转义,而Unicode的则没有.假设我可以简单地说:

>>> escaped = my_string.encode('unicode-escape').replace("'", "\\'")
Run Code Online (Sandbox Code Playgroud)

......并获得预期的行为?

编辑:只是为了超级清晰,预期的行为是获得适合作为文字的东西.

Mik*_*ers 24

根据我对CPython 2.6.5源代码的实现unicode-escape和unicode的解释repr,是的; repr(unicode_string)和之间的唯一区别unicode_string.encode('unicode-escape')是包含报价和转义使用的报价.

它们都是由同一个函数驱动的unicodeescape_string.此函数采用一个参数,其唯一功能是切换包装引号的添加和该引用的转义.


ken*_*ytm 13

在0≤c<128的范围内,是的,这'是CPython 2.6的唯一区别.

>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])
Run Code Online (Sandbox Code Playgroud)

在此范围之外,这两种类型不可交换.

>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)

>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode
Run Code Online (Sandbox Code Playgroud)

在Python 3.x上,string_escape编码不再存在,因为str只能存储Unicode.

  • 那只是因为 '\x80' 不是有效的 ascii 编码字符串。尝试 `u'\x80'.encode('unicode-escape')` 并得到 `'\\x80'` (2认同)