代码之家  ›  专栏  ›  技术社区  ›  Mike Boers

Python“string\u escape”与“unicode\u escape”

  •  23
  • Mike Boers  · 技术社区  · 16 年前

    According to the docs string_escape :

    …而 unicode_escape

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

    >>> print """before '" \0 after""".encode('string-escape')
    before \'" \x00 after
    >>> print """before '" \0 after""".encode('unicode-escape')
    before '" \x00 after
    

    这个 字符串\u转义

    >>> escaped = my_string.encode('unicode-escape').replace("'", "\\'")
    

    …得到预期的行为?

    非常清楚的是,预期的行为是得到一些合适的文字。

    2 回复  |  直到 8 年前
        1
  •  26
  •   Mike Boers    16 年前

    unicode-escape repr 在cpython2.6.5源代码中,是;唯一的区别是 repr(unicode_string) unicode_string.encode('unicode-escape') 包含换行引号和转义引号。

    它们都是由相同的功能驱动的, unicodeescape_string

        2
  •  14
  •   kennytm    16 年前

    在0范围内¤ c<128,是的 ' 是cpython2.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