首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python "string_escape“vs "unicode_escape”

Python "string_escape“vs "unicode_escape”
EN

Stack Overflow用户
提问于 2010-06-04 03:18:48
回答 2查看 114K关注 0票数 27

编码string_escape的内置字符串According to the docs

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

...while the unicode_escape

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

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

代码语言:javascript
复制
>>> print """before '" \0 after""".encode('string-escape')
before \'" \x00 after
>>> print """before '" \0 after""".encode('unicode-escape')
before '" \x00 after

string_escape转义单引号,而Unicode不转义。可以假定我可以简单地:

代码语言:javascript
复制
>>> escaped = my_string.encode('unicode-escape').replace("'", "\\'")

...and得到了预期的行为吗?

编辑:非常清楚,预期的行为是获得一些适合的文字。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-06-09 07:06:47

根据我对unicode-escape和CPython 2.6.5源代码中unicode repr实现的解释,是的;repr(unicode_string)unicode_string.encode('unicode-escape')之间唯一的区别是包含了换行引号和转义引号。

它们都是由同一个函数unicodeescape_string驱动的。此函数接受一个参数,该参数的唯一功能是切换添加换行引号和转义该引号。

票数 26
EN

Stack Overflow用户

发布于 2010-06-04 03:32:14

在0≤c< 128的范围内,'是CPython 2.6的唯一不同之处。

代码语言:javascript
复制
>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])

超出此范围的两种类型不能互换。

代码语言:javascript
复制
>>> '\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。

票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2969044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档