Is X = b'ABC 'equivalent to x =' ABC'.encode ("ascii") in python3.5?
3 answers
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 to share
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 to share