Python 3:如何获得字节字符串的字符串文字表示?

Mar*_*itz 7 python escaping python-3.x

在Python 3中,如何将字节字符串插入到常规字符串中并获得与Python 2相同的行为(即:只获取没有b前缀或双反斜杠的转义码)?

例如:

Python 2.7:

>>> x = u'\u041c\u0438\u0440'.encode('utf-8')
>>> str(x)
'\xd0\x9c\xd0\xb8\xd1\x80'
>>> 'x = %s' % x
'x = \xd0\x9c\xd0\xb8\xd1\x80'
Run Code Online (Sandbox Code Playgroud)

Python 3.3:

>>> x = u'\u041c\u0438\u0440'.encode('utf-8')
>>> str(x)
"b'\\xd0\\x9c\\xd0\\xb8\\xd1\\x80'"
>>> 'x = %s' % x
"x = b'\\xd0\\x9c\\xd0\\xb8\\xd1\\x80'"
Run Code Online (Sandbox Code Playgroud)

注意如何使用Python 3,我b在输出中获得前缀和双下划线.我想得到的结果是我在Python 2中获得的结果.

Mar*_*ers 5

在您的 Python 3 示例中,您插入的是 Unicode 字符串,而不是像您在 Python 2 中所做的那样的字节字符串。

在 Python 3 中,bytes不支持插值(字符串格式或你有什么)。

要么串联,要么一直使用 Unicode 并且仅在您进行插值时进行编码:

b'x = ' + x
Run Code Online (Sandbox Code Playgroud)

或者

'x = {}'.format(x.decode('utf8')).encode('utf8')
Run Code Online (Sandbox Code Playgroud)

或者

x = '\u041c\u0438\u0440'  # the u prefix is ignored in Python 3.3
'x = {}'.format(x).encode('utf8')
Run Code Online (Sandbox Code Playgroud)


jav*_*vex 5

在Python 2中,您有类型strunicodestr表示一个简单的字节字符串,而unicode表示Unicode字符串。

对于Python 3,这改变了:现在str是什么unicode在Python 2 byte是什么str在Python 2。

因此,当您这样做时("x = %s" % '\u041c\u0438\u0440').encode("utf-8"),实际上可以忽略u前缀,因为它是隐式的。python中未明确转换的所有内容均为unicode。

这将产生Python 3的最后一行:

 ("x = %s" % '\u041c\u0438\u0440').encode("utf-8")
Run Code Online (Sandbox Code Playgroud)

现在,我要如何在最终结果之后进行编码,这就是您应该始终做的事情:取出一个传入对象,将其解码为unicode(无论如何操作),然后在进行输出时,以您选择的编码对其进行编码。不要尝试处理原始字节字符串。那只是丑陋和过时的行为。