编码string_escape的内置字符串According to the docs
生成适合作为Python源代码中的字符串文字的字符串
...while the unicode_escape
生成的字符串适合作为Python源代码中的Unicode文本
所以,它们应该有大致相同的行为。但是,他们似乎以不同的方式对待单引号:
>>> print """before '" \0 after""".encode('string-escape')
before \'" \x00 after
>>> print """before '" \0 after""".encode('unicode-escape')
before '" \x00 afterstring_escape转义单引号,而Unicode不转义。可以假定我可以简单地:
>>> escaped = my_string.encode('unicode-escape').replace("'", "\\'")...and得到了预期的行为吗?
编辑:非常清楚,预期的行为是获得一些适合的文字。
发布于 2010-06-09 07:06:47
根据我对unicode-escape和CPython 2.6.5源代码中unicode repr实现的解释,是的;repr(unicode_string)和unicode_string.encode('unicode-escape')之间唯一的区别是包含了换行引号和转义引号。
它们都是由同一个函数unicodeescape_string驱动的。此函数接受一个参数,该参数的唯一功能是切换添加换行引号和转义该引号。
发布于 2010-06-04 03:32:14
在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(["'"])超出此范围的两种类型不能互换。
>>> '\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在Python3.x上,string_escape编码不再存在,因为str只能存储Unicode。
https://stackoverflow.com/questions/2969044
复制相似问题