Is X = b'ABC 'equivalent to x =' ABC'.encode ("ascii") in python3.5?

Is it x = b'ABC'

equivalent x='ABC'.encode("ascii")

in Python 3.5? Are there any differences between these two methods.

+3


source to share


3 answers


They give the same result:

>>> 'ABC'.encode("ascii")
b'ABC'
>>> b'ABC'
b'ABC'

      



However, encode()

will call the encoder at run time, not at compile time.

+3


source


A quick test in Python 3 shows that they are indeed equivalent:

In [1]: x = b'ABC'

In [2]: y = 'ABC'.encode('ascii')

In [3]: x == y
Out[3]: True

In [4]: type(x)
Out[4]: bytes

In [5]: type(y)
Out[5]: bytes

      

According to the official python documentation :



Boolean literals are always prefixed with "b" or "B"; they generate an instance of type bytes instead of type str. They can only contain ASCII characters; bytes with a numeric value of 128 or higher must be expressed using screens.

So if all characters in the unicode string are ASCII, they will be treated the same way.

+2


source


Yes and no. Yes, for your specific example, the two are equivalent in that they give the same result.

For general use, however, they have some subtle differences. For example, consider the various ways to handle attempts to encode non-ascii characters:

@>>> b'Æ'
  File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
@>>> 'Æ'.encode("ascii")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character '\xc6' in position 0: ordinal not in range(128)

      

0


source







All Articles