What does the 'b' character do in front of a string literal in Python?


A string is a collection of characters that can represent a single word or a complete phrase. Since you can directly assign strings in Python to a literal (unlike other technologies) it is easy to use them.

Python includes a number of built in functions and methods to perform various operations on strings, a string is an object of the String class, which contains these methods.

In this article, we are going to find out what is the b character that is present in front of a string literal does in python.

The b literal in front of the string literal means that the given string is in bytes’ format. The b literal converts string into byte format. In this format bytes are actual data and string is an abstraction. A byte is a collection of 8 bits. A string is a collection of Unicode characters (UTF – 16, UTF 32) or ASCII, whereas a byte is a collection of octets (0 255).

The advantage of this process is that if we create a byte object it is directly stored in the computer’s disk, whereas if a string object is created it is first converted into a byte object then it is stored. So, by directly creating a byte object we are saving time.

In Python 2, the prefix 'b' or 'B' is disregarded. Bytes literals in Python 3 are always prefixed with 'b' or 'B', and they yield a bytes type instance rather than a str type instance. They can only contain ASCII characters, and bytes with a numeric value of 128 or more must use escapes. Python 3.x distinguishes between the following types −

literals = a series of Unicode characters str = '...' (UTF 16 or UTF 32)
literals = a series of octets bytes = b'..' (integers between 0 and 255)

Example

In the example given below, we are taking 2 input strings and checking if they are of same data type after the addition of b literal.

str1 = "Welcome to Tutorialspoint" str2 = b"Welcome to Tutorialspoint" print("The data type of the first string is") print(type(str1)) print("The data type of the second string is") print(type(str2))

Output

The output of the above example is,

The data type of the first string is
<class 'str'>
The data type of the second string is
<class 'bytes'>

Updated on: 25-Oct-2022

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements