In this tutorial let’s learn about How and why ‘b’ Character in Front of String in Python. Strings in Python can be used to describe data in a human-readable format, such as characters, words or special characters. Bytes on the other hand, should be used to define low-level binary data structures.
Why ‘b’ Character is used in Front of String in Python
In Python, the b” notation is used to specify a bytes string. In contrast to normal strings, which include ASCII characters, a bytes string is an array of byte variables with hexadecimal values ranging from 0 to 255.
We may also use the encode() function to convert normal strings to bytes strings. The program below demonstrates how to use the encode() method to convert normal strings into bytes strings.
string = 'Python string example' print(string.encode())
b’Python string example’
In the above example we have encoded the regular string
Python string example into a
bytes string format with the
encode() function. The b” statement can also be used to encode a string into a bytes string format. The code snippet below shows how we can implement this.
string = b'Python string example' print(string)
b’Python string example’
Python b string
Python b strings are mainly composed of bytes, which implies that the literals that represent integers range from 0 to 255. The data type of Python b string and Python string differs significantly. The regular string contains a sequence of Unicode characters such as UTF-16 or UTF-32, whereas the Python b string contains bytes data type literals that represent numbers ranging from 0 to 255.
By adding that prefix b in front of a regular string in python, we are modifying its data type from string to bytes.
Code Example :
string = 'Python string example' print('type :',type(string)) bytes_string = b'Python string example' print('type :',type(bytes_string))
type : <class ‘str’>
type : <class ‘bytes’>
b character in front of string in python 2 and python 3
As per python 2.x Documentation the b string is stated as :
A prefix of ‘b’ or ‘B’ is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3 (e.g. when code is automatically converted with python 2to python 3). A ‘u’ or ‘b’ prefix may be followed by an ‘r’ prefix.
As per python 3 Documentation the b string is stated as :
Bytes literals are always prefixed with ‘b’ or ‘B’; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.
In this tutorial we learnt about the python b string and why the b character is used in front of strings in python. You can convert string to bytes and bytes to strings using encode() and decode() functions with proper encodings like UTF-8 etc. To convert bytes to string refer How to Convert Bytes to String in Python .
Set Comprehension in Python
Create Empty List in Python