Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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. The string literals are typically enclosed in quotes (' ' or " ") and they represent a sequences of characters.
However, in some scenarios we will encounter a string that starts with a lowercase b for example, b'WELCOME', Where the b prefix stands for bytes literal.
Bytes literals are useful when dealing with binary data, where data is transmitted or received in byte format rather than as human-readable text. In this article , we'll explore what the b character do in front of a string literal.
Bytes Literal
The string prefixed with b is not a regular string, it is a bytes object. Unlike the regular strings, which represent the Unicode text, the bytes object is the sequence of raw byte values ranging from 0 to 255.
The byte literals are immutable and are efficient for handling the low-level binary data.
Example 1
Let's look at the following example, where we are going to create the byte literal.
demo = b'TutorialsPoint' print(demo) print(type(demo))
Output
Output of the above program is as follows -
b'TutorialsPoint' <class 'bytes'>
Example 2
Consider the following example, where we are going to compare the strings and bytes.
demo1 = b'Welcome' demo2 = 'Welcome' print(demo1 == demo2)
Output
Output of the above program is as follows -
False
Example 3
In the following example, we are going to decode the byte into the string.
demo = b'Vanakam'
Result = demo.decode('utf-8')
print(Result)
print(type(Result))
Output
Following is the output of the above program -
Vanakam <class 'str'>
