0

In python 2.7:

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

In python 3.4:

>>> x1='\xba\xba'
>>> x2=b'\xba\xba'
>>> x1==x2
False
>>> type(x1)
<class 'str'>
>>> type(x2)
<class 'bytes'>
  1. how to change x1 into x2?
  2. how to change x2 into x1?

2 Answers 2

1

In Python 3.x, use str.encode (str -> bytes) and bytes.decode (bytes -> str) with latin1 encoding (or iso-8859-1):

>>> x1 = '\xba\xba'
>>> x2 = b'\xba\xba'
>>> x1.encode('latin1') == x2
True
>>> x2.decode('latin1') == x1
True
Sign up to request clarification or add additional context in comments.

4 Comments

'\xba\xba'.encode('latin1') -> UnicodeDecodeError on Python 2.
@J.F.Sebastian, in Python 2.x, '\xba\xba' == b'\xba\xba' (assuming no from __future__ import unicode_literals); no need to encode it. They are both byte strings.
The quesiton has code in both Python 2 and 3. You should specify the Python version you expect the code example to work if your code can't work on both.
@J.F.Sebastian, The question title mentioned Python 3. Anyway, I will specify the version. Thank you for the suggestion.
1

Both x1 and x2 are bytestrings in Python 2. If you compare Unicode and bytes on Python 2; you also get False in this case:

>>> 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 is a Unicode string in Python 3.

You could add from __future__ import unicode_literals to make the code work the same on both Python 2 and 3:

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

Don't mix bytestrings and Unicode strings.

To convert Unicode string to bytes:

bytestring = unicode_string.encode(character_encoding)

To convert bytes to Unicode string:

unicode_string = bytestring.decode(character_encoding)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.