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 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 does in front of a string literal.
What is a Bytes Literal?
The string prefixed with b is not a regular string, it is a bytes object. Unlike regular strings, which represent Unicode text, the bytes object is a sequence of raw byte values ranging from 0 to 255.
Byte literals are immutable and are efficient for handling low-level binary data.
Creating Bytes Literals
Let's look at an example where we create a byte literal ?
demo = b'TutorialsPoint' print(demo) print(type(demo))
The output of the above code is ?
b'TutorialsPoint' <class 'bytes'>
Strings vs Bytes Comparison
Regular strings and bytes are different types and cannot be directly compared ?
demo1 = b'Welcome'
demo2 = 'Welcome'
print(demo1 == demo2)
print(f"Type of demo1: {type(demo1)}")
print(f"Type of demo2: {type(demo2)}")
The output of the above code is ?
False Type of demo1: <class 'bytes'> Type of demo2: <class 'str'>
Converting Bytes to Strings
You can convert bytes to strings using the decode() method ?
demo = b'Vanakam'
result = demo.decode('utf-8')
print(result)
print(type(result))
The output of the above code is ?
Vanakam <class 'str'>
Converting Strings to Bytes
Similarly, you can convert strings to bytes using the encode() method ?
text = "Hello World"
byte_data = text.encode('utf-8')
print(byte_data)
print(type(byte_data))
The output of the above code is ?
b'Hello World' <class 'bytes'>
Common Use Cases
Bytes literals are commonly used in:
- File I/O operations − Reading binary files like images, videos
- Network communication − Sending data over sockets
- Cryptography − Handling encrypted data
- Data serialization − Converting objects to binary format
Conclusion
The 'b' prefix creates a bytes literal, which represents binary data as a sequence of byte values. Use bytes for binary operations and strings for text processing. Convert between them using encode() and decode() methods.
