繁体   English   中英

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

[英]Python 3: How do I get a string literal representation of a byte string?

在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'

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'"

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

在Python 2中,您有strunicode类型。 str表示简单的字节字符串,而unicode是Unicode字符串。

对于Python 3,这改变了:现在str是Python 2中的unicode ,而byte是Python 2中的str

因此,当您执行("x = %s" % '\М\и\р').encode("utf-8")您实际上可以省略u前缀,因为它是隐式的。 未在python中显式转换的所有内容都是unicode。

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

 ("x = %s" % '\u041c\u0438\u0440').encode("utf-8")

现在我如何在最终结果之后进行编码,这是你应该经常做的事情:获取一个传入的对象,将其解码为unicode(如何做到这一点),然后在进行输出时,按照您选择的编码对其进行编码。 不要尝试处理原始字节字符串。 这只是丑陋和弃用的行为。

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

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

要么连接,要么全部使用Unicode,只在插值时进行编码:

b'x = ' + x

要么

'x = {}'.format(x.decode('utf8')).encode('utf8')

要么

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

在Python 2中,字节字符串和常规字符串是相同的,因此str()不进行转换。 在Python 3中,字符串始终是Unicode字符串,因此字节字符串的str()进行转换。

您可以进行自己的转换,而不是按照自己的意愿行事:

x2 = ''.join(chr(c) for c in x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM