Table of Contents
Prefix b Before String in Python
Prefix b before String denotes a byte String. By putting b before String, you can convert String to bytes in Python.
The upgrade from Python 2 to Python 3 was considered a major change as many new features were introduced and quite a few changes were done to the existing types. One such change was the distinction between bytes and strings in Python 3.
In Python 2, bytes and strings were considered the same, and both were used interchangeably. They were considered as a collection of octets in this version which means that they were ASCII encoded. To create Unicode string literals one had to use the u
prefix before the string.
However, Python 3 introduced a major change as strings were now considered a collection of Unicode characters. This provided users with a wide range of characters to choose from and represent strings as texts.
Bytes are treated as a separate entity in Python 3 and we have to use the prefix b
before string in Python to create them. The b
prefix tells the interpreter to create a bytes
object.
For example,
1 2 3 4 |
s = b'bytes string' print(s) |
Output:
In the above example, we can notice the prefix b
before string in Python which indicates that it is a byte string.
We can also use the bytes()
and bytearray()
functions to create a bytes instance of the required sequence. Here we need to specify the source for the object. If the source is a string, we need to specify the encoding of the same as well.
The difference between the above-mentioned functions is that the object returned by the bytes()
function cannot be modified whereas the object returned by the latter can be altered.
Further reading:
Conclusion
In this tutorial, we discussed the prefix b
before string in Python. First, we highlighted the difference in Python 2 and 3 regarding the treatment of bytes. We discussed the distinction between bytes and strings in Python 3 and how the prefix b
before string in Python can create a bytes instance. We also highlighted the use of bytes()
and bytearray()
functions.