【问题标题】:change between string and bytes in python3python3中字符串和字节之间的变化
【发布时间】:2015-03-16 10:16:51
【问题描述】:

在 python 2.7 中:

>>> x1= '\xba\xba'
>>> x2=b'\xba\xba'
>>> x1==x2
True

在 python 3.4 中:

>>> x1='\xba\xba'
>>> x2=b'\xba\xba'
>>> x1==x2
False
>>> type(x1)
<class 'str'>
>>> type(x2)
<class 'bytes'>
  1. 如何将x1改为x2
  2. 如何将x2改为x1

【问题讨论】:

    标签: python string python-3.x unicode bytearray


    【解决方案1】:

    在 Python 3.x 中,使用带有 latin1 编码(或 iso-8859-1)的 str.encode (str -> bytes) 和 bytes.decode (bytes -> str):

    >>> x1 = '\xba\xba'
    >>> x2 = b'\xba\xba'
    >>> x1.encode('latin1') == x2
    True
    >>> x2.decode('latin1') == x1
    True
    

    【讨论】:

    • '\xba\xba'.encode('latin1') -> UnicodeDecodeError 在 Python 2 上。
    • @J.F.Sebastian,在 Python 2.x 中,'\xba\xba' == b'\xba\xba'(假设没有 from __future__ import unicode_literals);无需对其进行编码。它们都是字节字符串。
    • 该问题在 Python 2 和 3 中都有代码。如果您的代码不能同时在这两个版本上运行,您应该指定您希望代码示例运行的 Python 版本。
    • @J.F.Sebastian,问题标题提到了Python 3。无论如何,我会指定版本。谢谢你的建议。
    【解决方案2】:

    x1x2 在 Python 2 中都是字节串。如果在 Python 2 上比较 Unicode 和字节;在这种情况下,您还会得到 False

    >>> u'\xba\xba' == b'\xba\xba'
    __main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
    False
    

    x1 是 Python 3 中的 Unicode 字符串。

    您可以添加 from __future__ import unicode_literals 以使代码在 Python 2 和 3 上的工作方式相同:

    >>> from __future__ import unicode_literals
    >>> x1 = '\xab\xab'
    >>> type(x1)
    <type 'unicode'>
    

    不要混合使用字节串和 Unicode 字符串。

    将 Unicode 字符串转换为字节:

    bytestring = unicode_string.encode(character_encoding)
    

    将字节转换为 Unicode 字符串:

    unicode_string = bytestring.decode(character_encoding)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多